I have a method that should return the ids from a List.
Usually I would use reflection for this task (I cannot use a generic method since the classes are usually POCOS that don't share an interface or a base class and I can't modify them). However, I thought about the new dynamic
keyword and wanted to try this.
However my problem is that dataSource[index] returns an object. Well at runtime it is ensured that the object isself is on of my own classes and has a id property.
But I suppose because the method returns an object, I get a RumtineBinderException at runtime while accessing current.id
public List<int> GetItemIds()
{
var result = new List<int>();
var dataSource = GetDataSource(); // returns an List<Object>
for (int i = 0; i <= dataSource.Count - 1; i++)
{
dynamic current = dataSource[i];
int id = current.Id; // throws RuntimeBinderException: Object has no definition for id
}
return result;
}
Is there a way to achive what I want or do I have to go back to reflection to get the id property?
Update:
current.GetType() returns object
current.GetType().GetProperties() returns a TargetInvocationException
My Pocos live in my main project (VB.net) but this method is in a class libary, maybe that is the cause. However:
object current = dataSource[i];
PropertyInfo prop = current.GetType().GetProperty("id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (prop != null)
{
int id = (int)prop.GetValue(current, null);
}
works.