Wednesday, March 24, 2010

Using as to Test Types

The operator as is used to convert an expression to a specified reference type. It is used according to the form:
expression as type
where:
type is a reference type.
expression is the object to be converted.
If the conversion is successful, it returns the value of the expression; null otherwise.
This expression is equivalent to casting expression with type except that it doesn’t throw an exception if the conversion fails. The expression is equivalent to the following conditional expression:
expression is type ? (type) expression : (type) null;
In the following example, the method TestType is used to test objects of various types. Notice that only reference – type objects are converted.
Example 8-4
//Example 8-4.cs
// The as operator
using System;
public class MyClass
{
    static void TestType(object o)
    {
        if(o as MyClass != null)
            Console.WriteLine(“The object \”{0}\” is a class.”, o);
        else if ( o as string != null)
            Console.WriteLine(“The object \”{0}\” is a string.”, o);
        else
            Console.WriteLine(“The object \”{0}\” is not a reference type.”, o);
    }
    static void Main()
    {
        MyClass mc = new MyClass();
        string myString = “Hello, World!”;
        int myInt = 123;
        TestType(mc);
        TestType(myString);
        TestType(myInt);
    }
}

No comments:

Post a Comment