Use the is operator in C#

[is operator]

The is operator lets you determine whether you can convert an object to a particular type. For example, suppose the Student class inherits from Person, and that student and person are objects from the obvious classes. Then, for example, the statement student is Person returns true because the object student can be converted into a Person object (because a Student object is a kind of Person object).

This program uses the following code to demonstrate the is statement.

private void Form1_Load(object sender, EventArgs e)
{
    Person person = new Person();
    Student student = new Student();
    object obj = student;

    if (student is Student)
        lstResults.Items.Add("a_student is a Student");
    else
        lstResults.Items.Add("a_student is not a Student");

    if (student is Person)
        lstResults.Items.Add("a_student is a Person");
    else
        lstResults.Items.Add("a_student is not a Person");

    if (person is Person)
        lstResults.Items.Add("a_person is a Person");
    else
        lstResults.Items.Add("a_person is not a Person");

    if (person is Student)
        lstResults.Items.Add("a_person is a Student");
    else
        lstResults.Items.Add("a_person is not a Student");
}

Alternatively you can use the as keyword to try to convert an object into another type. For example, the following statement tries to convert a Person object into a Student object.

Student student = person as Student;

In this example the conversion fails because a Person cannot be converted into a Student. In that case the as keyword returns null so the variable student ends up containing null and your code can look for that value.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in classes, OOP, syntax and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *