5

Possible Duplicate:
Type Checking: typeof, GetType, or is?

So I am comparing a Control's type and I thought I could do something like this.

if (control[0].GetType() is TSendForReview)

However, I get the following warning.

The given expression is never of the provided ('MyApp.Controls.TSendForReview') type    

So if I switch it to this the warning goes away.

if (control[0].GetType() == typeof(TSendForReview))

What exactly does that warning mean and what is the difference between typeof and is while comparing control types.

Community
  • 1
  • 1
Steven Combs
  • 1,890
  • 6
  • 29
  • 54
  • possible duplicate of http://stackoverflow.com/questions/7765372/what-is-the-difference-between-typeof-and-the-is-keyword or [Type Checking: typeof, GetType, or is?](http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is) – Tim Schmelter Jul 19 '12 at 20:49

2 Answers2

8

GetType returns an instance of System.Type and this is never an instance of TSendForReview. You probably want to use

if(control[0] is TSendForReview)

to see if the control is an instance of your type.

Your modified version gets the runtime type of the control and compares it to the type instance for TSendForReview. This is not the same as using is since it must have the exact type, whereas is will return true for a subtype of TSendForReview.

And why the warning?

The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.

Source: MSDN

Lee
  • 142,018
  • 20
  • 234
  • 287
0

The IS operator will return true for all objects that implement a given type. The GetType function returns a type instance for the object. So depending on your scenario would determine how you want to perform your type checking.

Take the following code

public interface IFoo { }
public class Foo : IFoo { }
public class FooDerived : Foo { }

Then the following check will always be false as IFoo is an interface (same applies to abstract classes) because there is no concrete implementation. Which may be what the compiler is yelling at.

obj.GetType() == typeof(IFoo)

If the check was the following, it would be true for both Foo and FooDerived, and false for everything else.

obj is IFoo

If you want to make sure an object is of a specific type, and not any object that implements the type you would want to perform the check like the following, which would be true for Foo but not for FooDerived.

obj.GetType() == typeof(Foo)
JG in SD
  • 5,427
  • 3
  • 34
  • 46