Search code examples
c#reflectiongetvalue

C# Reflection GetField().GetValue()


Given the following:

List<T> someList;

Where T is a type of some class:

public class Class1
{
  public int test1;
}

public class Class2
{
  public int test2;
}

How would you use Reflection to extract the values of test1/test2 stored in each List item? (The field names are provided)

My Attempt:

print(someList[someIndex]
.GetType()
.GetField("test1")
.GetValue(someList) // this is the part I'm puzzled about. What kind of variable should i pass here?

The Error I'm getting: "Object reference not set to an instance of an object", and according to microsoft docs the variable I should pass to GetValue is "The object whose field value will be returned." - which is what I'm doing.

Thanks for reading!


Solution

  • Add {get;set;} to your properties public int test1 { get; set; }

    var t = someList[0].GetType().GetProperty("test1").GetValue(someList[0], null);
    

    I recommend you can use this method

    public class Class1
    {
        public int test1 { get; set; }
        public object this[string propertyName]
        {
            get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
            set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
        }
    }
    
    var value = someList[0]["test1"];