Snail
Snail

Reputation: 109

How to set value to protected property derived from abstract class? C#

I have a class which was derived from base class. To make some manipulations with it in unit tests I would like to change some protected properties with reflection. But when I'm trying to do this I have a System.MissingMethodException.

namespace FooNamespace
{
    public abstract class Foo
    {
        protected bool SomeProperty { get; set; }
    }
}
namespace BarNamespace
{
    public class Bar : Foo
    {  
    }
}

private void ChangeTheProtectedProperty()
{
    var obj = new BarNamespace.Bar();
    var propertyName = "SomeProperty";
    var value = true;

    Type t = obj.GetType();
    if (t.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) == null)
        throw new ArgumentOutOfRangeException(nameof(propertyName), string.Format("Property {0} was not found in Type {1}", nameof(propertyName), obj.GetType().FullName));
    t.InvokeMember(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, obj, new object[] { value! });
}

Upvotes: -1

Views: 63

Answers (1)

ssedlacek
ssedlacek

Reputation: 196

Properties cannot be invoked, you can't use t.InvokeMember. To set the value into the property via reflection, the PropertyInfo.SetValue(object obj, object value) method is used:

var obj = new BarNamespace.Bar();

var propertyName = "SomeProperty";

var value = true;

var property = t.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
??
throw new ArgumentOutOfRangeException(nameof(propertyName), string.Format("Property {0} was not found in Type {1}", nameof(propertyName), obj.GetType().FullName));

property.SetValue(obj, value);

Upvotes: 0

Related Questions