What is the difference between typeof and the is keyword?

Solution 1:

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

Solution 2:

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

Solution 3:

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

Solution 4:

  • 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