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.
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 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.
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.
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 Type
s 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
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With