How to compare types
Solution 1:
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:
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:
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:
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:
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