Getting value of an AutoProperty that has no getter using PropertyInfo.GetValue

975 views Asked by At

I am trying to get the value of a string property in a unit test. The problem is that the property has no getter. The property is also declared as an AutoProperty and has no backing field.

I am trying to use PropertyInfo.GetValue(...) in the System.Reflection namespace. However I get System.ArgumentException : Property Get method was not found.

I do not own the code of that type so I am unable to add a getter to the property.

How does one get the value of such a property?

2

There are 2 answers

1
decyclone On

You would somehow need to find the backing field that was auto-generated by compiler using Reflection. And then, using its FieldInfo you will be able to read its value. And I am not sure if it is possible at all.

OK, I have the solution:

With following class,

public class TestClass
{
    public String TestProperty { private get; set; }
}

and following extension method,

public static class ObjectExtensions
{
    public static Object GetPropertyValue(this Object obj, String propertyName)
    {
        if (obj == null) throw new ArgumentNullException("obj", "`obj` cannot be null");

        var fields = from f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
                     where f.Name.Contains(String.Format("<{0}>", propertyName))
                     select f;

        if (fields.Any())
        {
            return fields.First().GetValue(obj);
        }

        return null;
    }
}

You can achieve what you want by using following code:

TestClass obj = new TestClass() { TestProperty = "Test Value" };
Object value = obj.GetPropertyValue("TestProperty"); // value = "Test Value"
0
Damien_The_Unbeliever On

The property will have a backing field, it's just that we don't know it's name (and it's name will not be a valid identifier). If this is for a one-off task, then you might do well to crack it open using .NET reflector and find the field that's being set by the setter.

I don't think there's anything you can do via Reflection (unless you want to parse the IL method body of the setter to find which field it's setting