Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GetType() and typeof() constitute reflection?

Tags:

c#

.net

In C# reflection invariably starts with:

myInstance.GetType();

Or:

typeof(MyType);

To get the Type, then when one queries the info about the type e.g. getting properties, fields, attributes etc. they are certainly performing reflection.

However are the above calls reflection themselves?

I suppose in a academic sense the answer is yes - because you are reflecting on the type. So my second part to the question is: is it evaluated at run time and does it perform a heap allocation the first time? (I know subsequent calls to GetType() on the same type return the same Type instance so .NET must cache the result - but did it have to construct a new Type the first time it was called? Or this something performed at compile time?

like image 410
markmnl Avatar asked Jun 24 '14 01:06

markmnl


People also ask

Does GetType use reflection?

The most basic way to do reflection is to use the GetType() method, but we can also use reflection to get information about methods, constructors, properties, and more.

What is the difference between typeof and GetType?

Typeof() The type takes the Type and returns the Type of the argument. The GetType() method of array class in C# gets the Type of the current instance.

What is use of GetType in C#?

Object is the base class for all types in the . NET type system, the GetType method can be used to return Type objects that represent all .

What is reflection in programming C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


1 Answers

The object returned by myInstance.GetType() or typeof(MyType) is an object on the managed heap. So at some point at runtime the allocation must be made. The compiler obviously cannot do a managed heap allocation. (This is in contrast to C/C++ 'functions' like sizeof, where a value is substituted in by the compiler, resulting in no runtime overhead at all.)

So from this, you can conclude that the Type objects are either created at the point your assembly is loaded, or created 'on-demand' when you invoke methods like myInstance.GetType() or typeof(MyType) for the first time.

Which of these is it? As far as I know, it's not specified, so it's hard to say. GetType(), for example, is implemented in the runtime itself:

[MethodImpl(MethodImplOptions.InternalCall)]
public extern Type GetType();

Either way, at some point there will have to be the (extremely small) runtime overhead of allocating the Type object for MyType on the managed heap.

like image 138
Baldrick Avatar answered Sep 21 '22 10:09

Baldrick