Search code examples
c#cilreflection.emit

How to define 'value' property setter parameter


With the following C# code:

public interface IFoo
{
    int Bar
    {
        get;
        set;
    }
}

the property setter signature compiles to:

.method public hidebysig specialname newslot abstract virtual 
    instance void set_X (
        int32 'value'
    ) cil managed 
{
}

when inspected with ILSpy or ildasm.

If I attempt to generate an identical method signature using the System.Reflection.Emit API, the resulting input parameter name is either empty:

.method public hidebysig specialname newslot abstract virtual 
    instance void set_X (
        int32 ''
    ) cil managed 
{
}

(signature generated by ilspy)

... or a seemingly generated reference name (A_1 in this case):

.method public hidebysig newslot specialname abstract virtual 
    instance void  set_X(
        int32 A_1
    ) cil managed
{
}

(signature generated by ildasm)

How can I give the input parameter the name "value" like in the C# compiled example?


Here's the code I've used to generate the setter with:

PropertyBuilder property = typeDef.DefineProperty("X", PropertyAttributes.HasDefault, CallingConventions.HasThis, typeof(int), null);

MethodAttributes ma = MethodAttributes.Public 
                    | MethodAttributes.HideBySig 
                    | MethodAttributes.NewSlot 
                    | MethodAttributes.SpecialName 
                    | MethodAttributes.Abstract 
                    | MethodAttributes.Virtual;
MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

property.SetSetMethod(setMethod);

Even when I explicitly attempt to define the parameter name, the result is still the same:

MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

ParameterBuilder pb = setMethod.DefineParameter(0, ParameterAttributes.None, "value");

property.SetSetMethod(setMethod);

Solution

  • I think you have to use index 1 for the first parameter. From the msdn entry for MethodBuilder.DefineParameter Method:

    Remarks

    [...]

    Parameter numbering begins with 1, so position is 1 for the first parameter. If position is zero, this method affects the return value.