Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DynamicObject: Is there a way to access properties by index?

Is there a way to access the properties of a dynamic object by index?

List<dynamic> list = _dataStagingManager.GetStatusList(consoleSearch);
foreach (var row in list)
{
    Console.WriteLine(row[0]);
    Console.WriteLine(row[1]);
}

In this example, the property name of row[0] is different depending on the results from a stored procedure column alias.

like image 621
Abe Avatar asked Oct 09 '22 12:10

Abe


2 Answers

Unfortunately, no. Unlike runtime objects (which have an iterable collection of their members that can easily be reflected/queried against) dynamic objects, by default, have no such collection. They can be implemented in any way that allows their members to be accessed by name. There is no idea of indices with dynamic objects, provided you don't choose to implement them yourself.

If you wanted to, you could override the TryGetIndex method on your dynamic type to provide indexing support.

like image 160
Adam Maras Avatar answered Oct 12 '22 02:10

Adam Maras


In general, that's not possible. For example, you could create a dynamic object that has every possible property:

class AnythingGoes : DynamicObject
{
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = binder.Name;
        return true;
    }
}

There is a chance you will be able to get the list of properties. If the dynamic object is actually normal object (one that does not implement IDynamicMetaObjectProvider), normal reflection will work fine.

If the object actually is dynamic (implements IDynamicMetaObjectProvider), you could try calling GetDynamicMemberNames() on the DynamicMetaObject returned from GetMetaObject(). But, as the example above shows, this is not guaranteed to work.

like image 26
svick Avatar answered Oct 12 '22 02:10

svick