Monday, June 20, 2005

 

Runtime Type Identification - is operator

To determine whether an object is of a certain type: we can use the is operator. It will return a boolean result.

expr is type

Returns true if the expression object is of type type or has it derived from type, else it will return false.

This is an example:
using System;

class A { }
class B : A { }

class UseIs
{
public static void Main()
{
A a = new A();
B b = new B();

if (a is A)
Console.WriteLine("a is an A");
if (b is A)
Console.WriteLine("b is an A because it is derived from A");
if (a is B)
Console.WriteLine("Never will be displayed");
else
Console.WriteLine("a is not a B");

if (b is B)
Console.WriteLine("b is a B");
if (a is object)
Console.WriteLine("a is an Object");

}
}

(Taken from C#: The Complete Reference from Herbert Schildt).

The result is
a is an A
b is an A because it is derived from A
a is not a B
b is a B
a is an Object

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?