How to compare types

C#.Net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

You can use for it the is operator. You can then check if object is specific type by writing:

if (myObject is string)
{
  DoSomething()
}

Solution 3 - C#

You can compare for exactly the same type using:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof returns the Type object from a given class.

But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

Solution 4 - C#

If your instance is a Type:

Type typeFiled;
if (typeField == typeof(string))
{ 
    ... 
}

but if your instance is an object and not a Type use the as operator:

object value;
string text = value as string;
if (text != null)
{
    // value is a string and you can do your work here
}

this has the advantage to convert value only once into the specified type.

Solution 5 - C#

http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx

Console.WriteLine("typeField is a {0}", typeField.GetType());

which would give you something like

typeField is a String

typeField is a DateTime

or

http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArchediusView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#Rafal SpacjerView Answer on Stackoverflow
Solution 3 - C#GvSView Answer on Stackoverflow
Solution 4 - C#SyntonyView Answer on Stackoverflow
Solution 5 - C#dotalchemyView Answer on Stackoverflow