Setting a property {get;} using reflection in C#

Viewed 1028

I have a class in a 3rd party library with an only get; property.

public class Person
{
    public string Name {get;}
}

I want to set the Name property using Reflection or any other suitable method, but I do not know from where the Name gets its value. I mean I do not know if it has a backing field like this?

private string m_name;

or it is like this:

public string Name {get; private set;}

How can I set this?

1 Answers

You need to obtain a FieldInfo instance for the property's backing field and call the SetValue() method.

The Mono.Reflection library (available in Package Manager) will help you find the backing field.

If the Property is an auto-property, you can call the GetBackingField() extension method on the PropertyInfo instance.

Otherwise, you'll have to disassemble the IL of the MethodInfo of the getter like this:

var instructions = yourProp.GetGetMethod().GetInstructions();

This will give you a list of the method's IL instructions. If they look like this:

Ldarg0
Ldfld    (Backing Field)
Ret

Then the 2nd Instruction will give you the backing field. In code:

if (instructions.Count == 3 && instructions[0].OpCode == OpCodes.Ldarg_0 && instructions[1].OpCode == OpCodes.Ldfld && instructions[2].OpCode == OpCodes.Ret)
{
    FieldInfo backingField = (FieldInfo)instructions[1].Operand;
}

Otherwise, the property is probably computed and has no backing field.

Related