Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# dynamic method for an object

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.

like image 703
Jürgen Steinblock Avatar asked Jul 14 '11 15:07

Jürgen Steinblock


2 Answers

I believe you may need to define the return type of "GetDataSource()" as "List<dynamic>".

Of course, as stated in the comments, the objects must have the property "id" defined.

like image 161
Jason.Net Avatar answered Oct 17 '22 02:10

Jason.Net


C# is case sensitive including when you use the dynamic keyword. your call is int id = current.Id; but you talk about the property being lowercase id, and your reflection call looks case insensitive. The dynamic keyword should have no problem calling public instance properties even across assembly boundaries, since it says the method is not found my best guess is that you need to be using int id = current.id;

like image 26
jbtule Avatar answered Oct 17 '22 01:10

jbtule