Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does typeof(myType).TypeHandle use reflection?

Tags:

c#

If I wrote this code:

typeof(myType).TypeHandle 

Would it use reflection?

How much different from:

Type.GetType(string).TypeHandle

is it?

like image 814
Dane O'Connor Avatar asked Oct 03 '08 19:10

Dane O'Connor


1 Answers

Well, it really depends on what you mean by "reflection" - which isn't exactly strictly defined.

There are two parts to using typeof in the compiled code. The first is the use of the ldtoken which is an IL instruction described like this in the CIL spec:

The ldtoken instruction pushes a RuntimeHandle for the specified metadata token. The token shall be one of:

  • A methoddef, methodref or methodspec: pushes a RuntimeMethodHandle
  • A typedef, typeref, or typespec : pushes a RuntimeTypeHandle
  • A fielddef or fieldref : pushes a RuntimeFieldHandle
The value pushed on the stack can be used in calls to reflection methods in the system class library

After this, a call to Type.GetTypeFromHandle is made.

This is all significantly quicker than Type.GetType(string) however, if that's what you were concerned with.

EDIT: I just noticed the TypeHandle part of your question. As far as I can see, the MS compiler doesn't optimise away the call to GetTypeFromHandle and then TypeHandle, even though I guess you really only need the ldtoken call.

Whether all of this counts as "reflection" or not is up to you...

like image 139
Jon Skeet Avatar answered Sep 26 '22 21:09

Jon Skeet