Home Setting a property {get;} using reflection in C#
Reply: 1

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

Vahid
1#
Vahid Published in 2017-11-14 22:00:01Z

This question already has an answer here:

  • Changing read only properties with reflection 5 answers

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?

Mr Anderson
2#
Mr Anderson Reply to 2017-11-14 22:46:41Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.402964 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO