Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between typeof and the is keyword?

Tags:

c#

types

generics

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; } 
like image 348
Dennis Traub Avatar asked Oct 14 '11 09:10

Dennis Traub


People also ask

What is the difference between Typeof and GetType?

The only real difference here is that when you want to obtain the type from an instance of your class, you use GetType . If you don't have an instance, but you know the type name (and just need the actual System. Type to inspect or compare to), you would use typeof .

What is typeof in C#?

The C# typeof operator ( GetType operator in Visual Basic) is used to get a Type object representing String. From this Type object, the GetMethod method is used to get a MethodInfo representing the String. Substring overload that takes a starting location and a length.


2 Answers

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 
like image 129
gsharp Avatar answered Sep 19 '22 15:09

gsharp


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

like image 22
Jens Avatar answered Sep 19 '22 15:09

Jens