is keyword


I don’t know how I missed the is keyword in C#. I must have been asleep or something when I read about this. Up till now I’ve been getting the type of an object and comparing to the typeof() a class.

object foo = “bar”;

if (foo is string)
{
Console.WriteLine(“foo is a string”);
}

if (foo.GetType() == typeof(string))
{
Console.WriteLine(“foo is a string”);
}

Comments (3)

  1. I tend to use the ‘as’ keyword with a test for null. Reason is that when I’m checking a type, I usually want to go on and cast to that type – your example above is of course more suited for is…but say, sor example I want to cast to a string.

    string testString = testObject as string;

    if(testString != null)

    {

    //Do whatever I want with the string…

    }

  2. Ivan Towlson says:

    Note that "is" and "GetType() ==" do different things in the presence of derivation hierarchies.

    Thus:

    class Derived : Base { … }

    object foo = new Derived();

    (foo is Base) will return true

    (foo.GetType() == typeof(Base)) will return false

    Usually the "is" behaviour is what you want, which is another reason to avoid the GetType() approach.

  3. Omar Shahine says:

    Ivan, that is a great point and something I just used the other day. I was trying to do a comparison using (foo.GetType() == typeof(Base)) and it kept failing .