.NET Reflection set private property

Viewed 22552

If you have a property defined like this:

private DateTime modifiedOn;
public DateTime ModifiedOn
{
    get { return modifiedOn; }
}

How do you set it to a certain value with Reflection?

I've tried both:

dto.GetType().GetProperty("ModifiedOn").SetValue(dto, modifiedOn, null);

and

dto.GetType().GetProperty("modifiedOn").SetValue(dto, modifiedOn, null);

but without any success. Sorry if this is a stupid question but it's the first time I'm using Reflection with C#.NET.

6 Answers

If you have a private property with a setter then you can use this Extension method to set a value:

using System.Reflection;

public static class ObjectExtensions
{
    public static void SetPrivateValue<T>(this T obj, string propertyName, object value)
    {
        var type = typeof(T);
        type.GetTypeInfo().GetDeclaredProperty(propertyName).SetValue(obj, value, null);
    }
}

One way to do it, and this is might be the most correct way, considering that set may or may not exist, is to use a specific accessor

var myc = new MyClass();
var pi = typeof(MyClass).GetProperty("Prop1", BindingFlags.NonPublic | BindingFlags.Instance);

if (pi.SetMethod != null) // check if you have 'set' accessor
    pi.SetMethod.Invoke(myc, new object[]{ someValue });
else
{
    // do nothing OR
    throw new Exception("Attempted to set read-only property " + pi.Name);
}
Related