Inside your generic method, T is defined at runtime and thus you cannot write a code that access the property at compile time - thus the error.
BTW, If you access a hardcoded property in your Generic method, it kind of defeats the purpose of using Generic. Assume you want to use the same generic method ProcessMyList for another class Address and it does not have 'Name' property in it. What would happen then?
For learning purpose to resolve above, if you want to access properties from the Type passed (Fruit) here, you need to first get the type. Once you know the type, you can access property accordingly.
Option 1: Reflection
foreach (T thing in list)
{
var value = typeof(T).GetProperty("Name").GetValue(thing);
Console.WriteLine(obj.Name);
}
Option 2:
dynamic
keyword
foreach (T thing in list)
{
dynamic currobj = thing;
Console.WriteLine(currobj.Name);
}
In order to keep the method still generic,
- you can add an additional parameter of 'property name' to get and then use that during reflection.
- you can come up with a class design such that all classes that inherits from a defined interface or abstract class can use the above generic method.