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

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.

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

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");

Or:

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