Search code examples
c#reflectionpropertyinfo

Propertyinfo get value non static value requires target


Im trying to reflect some data from my properties and im having a hard time trying to figure out why im getting the error "non static value requires target" I have tried passing values into getvalue with no success. if i step through the code the properties are there, do not understand why the get vlue is throwing an error.

foreach (KeyValuePair<string, object> argument in actionArguments)
{
    Type type = argument.Value.GetType() as Type;
    PropertyInfo[] properties = type.GetProperties();

    Parallel.ForEach(properties, property =>
    {
        if (property.PropertyType == typeof(string))
        {
            string text = property.GetValue(null, null) as string; -- error 
            string[] words = text.Split(' ');
        }
    });
}

Solution

  • Because an instance property doesn't exist without an instance. So it is not possible to get a value of an instance property without providing an instance.If you are looking for static properties use BindingFlags.Static with GetProperties.

    If you have an instance you need to pass it to GetValue method instead of null:

    string text = property.GetValue(argument.Value) as string;