Search This Blog

Thursday, August 18, 2011

is and as operators in C#

is Operator:
  • is operator Checks if an object is compatible with a given type 
  • An is expression evaluates to true if the provided expression is non-null, and the provided object     can  be cast to the provided type without causing  an exception to be thrown.
as Operator:
  • The as operator is used to perform conversions between compatible reference types      
  • The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception
Ex:

public class Exam
{
    public string GetSubjectName()
    {
        return "C#";
    }
}
public class UnitTest
{
    public int GetTestNumber()
    {
        return 1;
    }
}

public partial class CSHARPSAMPLES_Keywords : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Exam e1 = new Exam();
    }
    public void Test(object o)
    {
        if (o is UnitTest)
        {
            UnitTest u = o as UnitTest;
            u.GetTestNumber();
        }
        else if (o is Exam)
        {
            Exam e = o as Exam;
            e.GetSubjectName();
        }
    }
}

2 comments:

Arvin Hindyar said...

Hello Sir,
Does it make any difference if we use
UnitTest u = new UnitTest();
instead of..
UnitTest u = o as UnitTest

Lok said...

In the First case you are directly creating object of given type.
Ex: UniTest u=new UnitTest();

In the second one you are trying cast the given o variable to type UnitTest class.