Search code examples
c#reflectionportable-class-library

Do all Type classes inherit from RuntimeType?


I want to know whether a on object of type Type is actually a type for a normal class (e.g. Object, Int32, etc.) or a type for a meta-object (e.g. typeof(Object), typeof(Int32), etc.).

By type of an object I mean:

Type t = typeof(Object);
Console.WriteLine("Type is {0}", t.FullName);

Type is System.Object

And by type of a type object, i.e. meta-object:

Type t = typeof(Object).GetType();
Console.WriteLine("Type is {0}", t.FullName);

Type is System.RuntimeType

I couldn't find any method/property in Type or TypeInfo to tell whether the object for which a Type object is made is actually a Type rather than a normal object.

If I have the object, I could do that:

bool IsType(object o) { return o is Type; }

But, I don't have the object itself, only its type.

I was hoping for something along the lines:

bool IsType(Type t) { return t.GetTypeInfo().IsType; }

But there's nothing like it, it seems..

So the only thing I can think of so far is:

bool IsType(Type type)
{
    // Can't use typeof(RuntimeType) due to its protection level
    Type runtimeType = typeof(Object).GetType();
    return runtimeType.Equals(type);
}

Yet, I can't be sure that GetType() for all objects of type Type would return RuntimeType, nor that they actually inherit from it...

Update

Let me explain it better. I'm writing a serializer. When serializing a class member (e.g. a field or a property), I'll have the field type (yet not the object). It's perfectly possible the member to be of type Type. I'd like to be able to serialize those objects as well.

For example a class like so:

class MyClass {
    private Type _cachedType;
}

I'll get the Type of the field _cachedType through reflection. How will I know that the object is a Type in the first place?


Solution

  • OK, I think the entire question reduces to

    How can I determine that a field is of type Type?

    As far as I can tell you don't care about the actual type of the values stored there because you will serialize all of them the same way ("then I can simply serialize them as strings using Type.AssemblyQualifiedName").

    Here you go:

    bool IsType(Type type)
    {
        return type == typeof(Type);
    }
    

    No need for a subclass check. The actual objects will be of a subclass but the field will have type Type.

    You can add the subclass check if you like:

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