Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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! });
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading