Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a class from a third-party library with a read-only property called Name. Here is the code for the class:

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

I want to set the value of the Name property using reflection or another suitable method, but I don't know how the property is implemented. Specifically, I don't know if it has a backing field like this:

private string m_name;

or if it is implemented like this:

public string Name {get; private set;}

How can I set the value of the Name property in this situation?

like image 995
Vahid Avatar asked Nov 29 '25 20:11

Vahid


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.

like image 138
Mr Anderson Avatar answered Dec 01 '25 11:12

Mr Anderson