Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between typeof and is when comparing object types? [duplicate]

Tags:

c#

types

controls

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.

like image 328
meanbunny Avatar asked Jul 19 '12 20:07

meanbunny


1 Answers

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

like image 107
Lee Avatar answered Nov 14 '22 22:11

Lee