Wednesday, March 24, 2010

Using is to Test Types

The operator is is used to test the type of various objects at run time. It is used in the following form:
expression is type
where:
type is a reference type.
expression is the object to be tested.
The result of this operation is either true of false.
For example, the following expression:
myObj is MyClass
is used to check if the object myObj is an instance of the class MyClass. The result of the expression renders true if it is an instance of MyClass; false otherwise.
Also, the expression:
myObj is MyInterface
is used to check if the object myObj is an instance of a class that implements the interface of a class that implements the interface IMyInterface. The result is either true of false.
In the following example, the operator is is used to check if the type if an object is an instance of MyClass and the two interfaces I1 and I2.
Example: -
//Example 8-3.cs
// The is operator
using System;
interface I1
{
}
interface I2
{
}
class Class1: I1, I2
{
}
class MyClass
{
    static bool TestType(object obj)
    {
        if (obj is l1 & obj is I2 & obj is Class1}
                return true;
        else
            return false;
    }
    public static void Main()
    {
        Class1 c = new Class1();
        Console.WriteLine(“The result of the test: {0}”, TestType(c ) );

    }
}

No comments:

Post a Comment