Categorized | C# FAQ

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();

        }

    }

}

EasyFreeAds Blog News Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

Leave a Reply