Does typeof (myType) .TypeHandle use reflection?

If I wrote this code:

typeof(myType).TypeHandle 

Will he use reflection?

How different from:

 Type.GetType(string).TypeHandle 

this is?

+4
source share
1 answer

Well, it really depends on what you mean by "reflection" - it is not exactly defined strictly.

There are two parts to compiling typeof in compiled code. First, the use of ldtoken , which is an IL statement, described similarly in the CIL specification:

The ldtoken command pushes the RuntimeHandle for the specified metadata token. The token must be one of:

  • Method def, methodref or methodpec: push RuntimeMethodHandle
  • Typed, typeref, or typespec: pushing RuntimeTypeHandle
  • Field field or fieldref: pushing RuntimeFieldHandle
The value inserted on the stack can be used when invoking reflection methods in the system class library

After that, a call to Type.GetTypeFromHandle .

All this is significantly faster than Type.GetType(string) , if that is what you were worried about.

EDIT: I just noticed a TypeHandle part of your question. As far as I can tell, the MS compiler does not optimize the GetTypeFromHandle call and then the TypeHandle call, although I think you really only need the ldtoken call.

Whether all this is considered a โ€œreflectionโ€ or not is up to you ...

+7
source

Source: https://habr.com/ru/post/1277452/


All Articles