Sponsored Ad

Tuesday, October 20, 2009

C# Is

An is formula measures to real if the offered formula is non-null, and the roffered object can be frame to the offered type without making an exclusion to be down.

The is keyword results in a compile-time warning if the construction is recognized to always be sure or to always be wrong, but typically measures type compatibility at running time. The is operator cannot be overloaded.

Example

// cs_keyword_is.cs
// The is operator.
using System;
class Class1
{
}
class Class2
{
}

class IsTest
{
    static void Test(object o)
    {
        Class1 a;
        Class2 b;

        if (o is Class1)
        {
            Console.WriteLine("o is Class1");
            a = (Class1)o;
            // Do something with "a."
        }
        else if (o is Class2)
        {
            Console.WriteLine("o is Class2");
            b = (Class2)o;
            // Do something with "b."
        }
        else
        {
            Console.WriteLine("o is neither Class1 nor Class2.");
        }
    }
    static void Main()
    {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();
        Test(c1);
        Test(c2);
        Test("a string");
    }
}

Output

o is Class1
o is Class2
o is neither Class1 nor Class2.

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers