45

What's the exact difference between the two?

// When calling this method with GetByType<MyClass>()

public bool GetByType<T>() {
    // this returns true:
    return typeof(T).Equals(typeof(MyClass));

    // this returns false:
    return typeof(T) is MyClass;
}
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • 14
    Warning - This won't work if you need to use inheritance. Using `typeof(AClass).IsAssignableFrom(typeof(T))` will solve that. See http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx. – Will Oct 14 '11 at 09:15
  • @Will thanks for the info. Wouldn't matter in my specific case, but good to know! – Dennis Traub Oct 14 '11 at 09:17

6 Answers6

61

You should use is AClass on instances and not to compare types:

var myInstance = new AClass();
var isit = myInstance is AClass; //true

is works also with base-classes and interfaces:

MemoryStream stream = new MemoryStream();

bool isStream = stream is Stream; //true
bool isIDispo = stream is IDisposable; //true
gsharp
  • 27,557
  • 22
  • 88
  • 134
33

The is keyword checks if an object is of a certain type. typeof(T) is of type Type, and not of type AClass.

Check the MSDN for the is keyword and the typeof keyword

Jehof
  • 34,674
  • 10
  • 123
  • 155
Jens
  • 25,229
  • 9
  • 75
  • 117
25

typeof(T) returns a Type instance. and the Type is never equal to AClass

var t1 = typeof(AClass)); // t1 is a "Type" object

var t2 = new AClass(); // t2 is a "AClass" object

t2 is AClass; // true
t1 is AClass; // false, because of t1 is a "Type" instance, not a "AClass" instance
amiry jd
  • 27,021
  • 30
  • 116
  • 215
11
  • typeof(T) returns a Type object
  • Type is not AClass and can never be since Type doesn't derive from AClass

your first statement is right

Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
10

typeof returns a Type object describing T which is not of type AClass hence the is returns false.

Joey
  • 1,752
  • 13
  • 17
10
  • first compares the two Type objects (types are themselves object in .net)
  • second, if well written (myObj is AClass) check compatibility between two types. if myObj is an instance of a class inheriting from AClass, it will return true.

typeof(T) is AClass returns false because typeof(T) is Type and AClass does not inherit from Type

VdesmedT
  • 9,037
  • 3
  • 34
  • 50