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?
You need to obtain a
FieldInfoinstance for the property's backing field and call theSetValue()method.The
Mono.Reflectionlibrary (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 thePropertyInfoinstance.Otherwise, you'll have to disassemble the IL of the
MethodInfoof the getter like this:This will give you a list of the method's IL instructions. If they look like this:
Then the 2nd Instruction will give you the backing field. In code:
Otherwise, the property is probably computed and has no backing field.