Mono.Cecil TypeReference to Type?

Will picture Will · Nov 15, 2010 · Viewed 8.4k times · Source

Is there anyways to go from a TypeReference in Mono.Cecil to a Type?

Answer

Johannes Rudolph picture Johannes Rudolph · Nov 15, 2010

In terms of "what's in the box" you can only have it the other way round, using the ModuleDefinition.Import API.

To go from a TypeReference to a System.Type you will need to manually look it up using Reflection and the AssemblyQualifiedName. Be aware that Cecil uses IL conventions to escape nested classes etc, so you need to apply some manual correction.

If you only want to resolve non-generic, non-nested types you should be fine though.

To go from a TypeReference to a TypeDefition (if that's what you meant) you need to to TypeReference.Resolve();


Requested Code Sample:

TypeReference tr = ... 
Type.GetType(tr.FullName + ", " + tr.Module.Assembly.FullName); 
// will look up in all assemnblies loaded into the current appDomain and fire the AppDomain.Resolve event if no Type could be found

The conventions used in Reflection are explained here, for Cecils conventions consult the Cecil Source Code.