If the Class2 extends Class1 it is very easy to make a simple logical error. For example, output of the following snippet is not what one would expect:
class Class1
{
}
class Class2 : Class1
{
}
class IsTest
{
static void Test(object o)
{
if (o is Class1)
{
Console.WriteLine("o is Class1");
}
else if (o is Class2)
{
Console.WriteLine("o is Class2");
}
}
static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Test(c1);
Test(c2);
}
}
Output would be:
o is Class1
o is Class1
That is so due to the fact that is operator returns true whenever an object can be cast to the given type. Since c2 can be cast to Class1, output is as stated. To make valid comparison, remember to always first check for derived types and only then base ones. Hence, correct way to check would be:
...
static void Test(object o)
{
// first check derived types
if (o is Class2)
{
Console.WriteLine("o is Class1");
}
else if (o is Class1)
{
Console.WriteLine("o is Class2");
}
}
...