I am trying to dynamically access properties of an object by using reflection:
class Program
{
private class MyClass
{
public int prop1 { get; set; } = 1;
public int prop2 { get; set; } = 2;
}
public static void Main()
{
var obj = new MyClass();
var propList = new List<string> { "prop1", "prop2"};
foreach (string propString in propList)
{
var prop = obj.GetType().GetProperty(propString);
// I get a compiler warning here: "Dereference of a possibly null reference."
Console.WriteLine((int)prop.GetValue(obj));
}
}
}
I would like to prevent the "null reference" warning in an appropriate way.
I have tried adding a if (prop == null) return;
check before the Console.WriteLine
, but that doesn't clear up the issue. Instead it turns the warning to "Unboxing a possibly null value".
Is there a way to enforce that the strings in propList are names of properties in MyClass? In that case, I would be comfortable silencing the warning with a ! since I would know that the property would always exist. In my mind this would be ideal, because then I would get a compiler error when creating the list.
CodePudding user response:
Looks like it's not just the prop
that may be null, but also the value returned by prop.GetValue(obj)
.
Try
var prop = obj.GetType().GetProperty(propString);
if (prop == null) return;
var o = prop.GetValue(obj);
if (o == null) return;
Console.WriteLine((int)o);
Or equivalent.