Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will GetType() return RunTimeType and when will it return the a Type like SampleProgram.MyClass1?

Tags:

c#

.net

I am learning about reflection and the GetType() method.

I notice that when I define types within an application and call the GetType() method it returns the type(class) of the object.

Class1 first = new Class1();
Class2 second = new Class2();
Type firstType = first.GetType();
Type secondType = second.GetType();
Console.WriteLine(firstType.ToString());//prints Class1
Console.WriteLine(secondType.ToString());//prints Class2

At the same time when I load another assembly using Assembly.LoadFrom() and iterate over the types using a foreach, the GetType() returns RunTimeType.

foreach (Type t in AddInAssembly.GetTypes())
{
    if (t.IsClass && typeof(IAddIn).IsAssignableFrom(t))
    {
        AddInTypes.Add(t);
        Console.WriteLine(t.GetType());//prints RunTimeType
    }
}

What is happening? Is My understanding wrong? Can anyone throw light on this behaviour.

like image 579
ckv Avatar asked Jan 21 '14 15:01

ckv


People also ask

What does GetType return in C#?

The C# GetType() method is used to get type of current object. It returns the instance of Type class which is used for reflection.

What is runtimeType?

What is runtimeType Property ? The runtimeType property is used to find out the runtime type of the object. The keyword var in Dart language lets a variable store any type of data. The runtimeType property helps to find what kind of data is stored in the variable using var keyword.

What is Runtime Type C#?

Here we discuss about a feature of C# called RTID (Runtime Type Identification). With the help of this, we can identify a type of an object during the execution of the program. And we can easily get that the casting is possible or not.


2 Answers

Maybe it will make more sense in this example:

Class1 someObj = new Class1();
Type type1 = someObj.GetType(); // Class1
Type type2 = type1.GetType(); // RuntimeType

In your first example, you're working with objects of type Class1 and Class2, so when you use GetType() it returns the Types representing Class1 and Class2.

In your second example, you're working with objects of type Type, which represent Class1 and Class2. When you use GetType() on these, it returns RuntimeType (which extends Type).

As further explanation, here are the types and contents of each variable after running my above example:

Variable | Type        | Content
someObj  | Class1      | N/A
type1    | RuntimeType | Class1
type2    | RuntimeType | RuntimeType
like image 169
Tim S. Avatar answered Sep 19 '22 00:09

Tim S.


GetType() returns the type of the instance you call it on.

t is a Type instance, so it returns the subclass of System.Type that t actually is (usually RuntimeType).

That's exactly like writing "4".GetType().GetType().

like image 33
SLaks Avatar answered Sep 18 '22 00:09

SLaks