Question

I am trying to get the property definition of an existing property setter. However, the SetMethod always seems to be null, even though I know it exists.

Here is my attempt so far:

public class Bar
{
    private Foo _foo;
    public virtual Foo Foo { get { return _foo; } { set { _foo = value; } }
}

var moduleDefinition = ModuleDefinition.ReadModule(assemblyFile);

var propertyTypeReference = new TypeReference(
    typeof(Foo).Namespace, 
    typeof(Foo).Name, 
    moduleDefinition, 
    null
);

var propertyDefinition = new PropertyDefinition(
    "Foo", 
    Mono.Cecil.PropertyAttributes.None, 
    propertyTypeReference
);

//always throws NullReferenceException because SetMethod is always null.
var instructions = propertyDefinition.SetMethod.Body.Instructions.ToList();

(I am running under the Microsoft .NET CLR).

How can I get the setter instruction of an existing property with Mono.Cecil?

Was it helpful?

Solution

You should get TypeDefinition for Foo from the ModuleDefinition.Types, and in turn get PropertyDefinition for Foo from the TypeDefinition.Properties. And later you can get the set method and its instructions.

Don't use any of the constructors, as they are used to build new metadata, not analyze existing. Calling them in your code in fact builds new references/definitions, and exceptions are expected as you did not build them correctly.

OTHER TIPS

You can try asm.MainModule.GetType("ClassFullname").Methods.First(m=>m.Name=="set_Foo")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top