Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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.
}

The as operator is similar to a cast operation; however, if the conversion is not possible, as returns null 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.

// 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

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

  • 6 Conversions

  • 7.9.10 The as operator

Community Additions

Show:
© 2017 Microsoft