How to compare types

Archedius picture Archedius · Mar 30, 2011 · Viewed 158k times · Source

Quick question: how to compare a Type type (pun not intended) with another type in C#? I mean, I've a Type typeField and I want to know if it is System.String, System.DateTime, etc., but typeField.Equals(System.String) doesn't work.

Any clue?

Answer

JaredPar picture JaredPar · Mar 30, 2011

Try the following

typeField == typeof(string)
typeField == typeof(DateTime)

The typeof operator in C# will give you a Type object for the named type. Type instances are comparable with the == operator so this is a good method for comparing them.

Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.