Share via


as (C# Reference) 

Used to perform conversions between compatible reference types. For example:

string s = someObject as string;

if (s != null)
{
    // someObject is a string.
}

Remarks

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form,

expression as type

is equivalent to,

expression is type ? (type)expression : (type)null

except that expression is evaluated only once.

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions.

Example

// cs_keyword_as.cs
// The as operator.
using System;
class Class1
{
}

class Class2
{
}

class MainClass
{
    static void Main()
    {
        object[] objArray = new object[6];
        objArray[0] = new Class1();
        objArray[1] = new Class2();
        objArray[2] = "hello";
        objArray[3] = 123;
        objArray[4] = 123.4;
        objArray[5] = null;

        for (int i = 0; i < objArray.Length; ++i)
        {
            string s = objArray[i] as string;
            Console.Write("{0}:", i);
            if (s != null)
            {
                Console.WriteLine("'" + s + "'");
            }
            else
            {
                Console.WriteLine("not a string");
            }
        }
    }
}

Output

0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 6 Conversions

  • 7.9.10 The as operator

See Also

Reference

C# Keywords
is (C# Reference)
?: Operator (C# Reference)
Operator Keywords (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference