Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a Type is of RunTimeType?

Tags:

c#

How do I determine if a Type is of type RunTimeType? I have this working but it is kind of kludgy:

    private bool IsTypeOfType(Type type)
    {
        return type.FullName ==  "System.RuntimeType";
    }
like image 572
Greg Finzer Avatar asked Apr 17 '12 00:04

Greg Finzer


1 Answers

I guess that you actually want to know if a Type object describes the Type class, but the Type object is typeof(RuntimeType) and not typeof(Type) and so comparing it to typeof(Type) fails.

What you can do is check if a instance of the type described by the Type object could be assigned to a variable of type Type. This gives the desired result, because RuntimeType derives from Type:

private bool IsTypeOfType(Type type)
{
    return typeof(Type).IsAssignableFrom(type);
}

If you really need to know the Type object that describes the Type class, you can use the GetType Method:

private bool IsRuntimeType(Type type)
{
    return type == typeof(Type).GetType();
}

However, because typeof(Type) != typeof(Type).GetType(), you should avoid this.


Examples:

IsTypeOfType(typeof(Type))                          // true
IsTypeOfType(typeof(Type).GetType())                // true
IsTypeOfType(typeof(string))                        // false
IsTypeOfType(typeof(int))                           // false

IsRuntimeType(typeof(Type))                         // false
IsRuntimeType(typeof(Type).GetType())               // true
IsRuntimeType(typeof(string))                       // false
IsRuntimeType(typeof(int))                          // false
like image 138
dtb Avatar answered Sep 28 '22 01:09

dtb