Skip to content

[question] System.Reflection.Metadata how to "resolve" a TypeReference? #28887

@jonathanpeppers

Description

@jonathanpeppers

Let's say I have:

  • Assembly Foo.dll with class Bar: public class Bar { }

If I grab Bar's TypeDefinition and look at BaseType:

//BaseType should be System.Object
var h = (TypeReferenceHandle)typeDefinition.BaseType;
var typeReference = reader.GetTypeReference (h);

If I want to get the TypeDefinition for System.Object here, I have to:

  • Get a MetadataReader for mscorlib.dll (that part is easy)
  • Loop over all the reader.TypeDefinitions and compare the full name...

If I need to do this a lot, such as a case of traversing base types... Is the only efficient way here to maintain my own mapping (or cache) of TypeDefinition and look them up for subsequent calls? Is there a better way to look up a TypeDefinition given the type's full name?

Mono.Cecil has a ResolveType() method that gives you a TypeDefinition from a TypeReference. It is a very different API, in general, though: https://github.com/jbevain/cecil/blob/1b79b96d29f1e8e9ba832191b1b42ea9cb750d20/Mono.Cecil/MetadataResolver.cs#L131-L154

Mono.Cecil uses "exported types" to look up TypeDefinition, but using SRM, reader.ExportedTypes.Count has been 0 for any assembly I've opened.

Any suggestions welcome!

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Reflection.MetadataquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions