GetProperty() returns null

My Problem: I have 5 properties I need to set and the code for each is identical except for a couple parameters. So rather than writing repeating code for each, I wanted to try reflection to set the values for all the parameters.

The properties are in the same class this code is running in, for example:

public MyClass
    public string? L1Value { get; set; }
    public string? L2Value { get; set; }
    public string? L3Value { get; set; }
    public string? L4Value { get; set; }
    public string? L5Value { get; set; }

    public void MethodToGetProperty()
        var result = GetType().GetPropterty(L1Value);

**In my actual code, I have a FOR loop that will dynamically create the parameter string name. However, I have to get this GetProperties() to work.

GetProperty(L1Value) is returning null. I used GetType().GetProperties() and I see all the properties and L1Value has a value.

The questions in Stackoverflow I found all point to either 1) it was a field, not a property (no getter or setter) or 2) the access modifier was incorrect or missing. Neither of these apply here.

enter image description here

I appreciate any suggestions you have.

>Solution :

In the GetProperty method you need to pass in the name of the property you want. For example:

var result = GetType().GetProperty("L1Value");


var result = GetType().GetProperty(nameof(L1Value));

Note this only give you the PropertyInfo object, so if you want the actual value, you will need to do this:

var value = result.GetValue(this);

Leave a Reply