Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

Accessing elements in a dynamic object in C#

I have a public function which returns a dynamic object. Such dynamic object is actually of type MyObj where MyObj is a private class of the class which contains the function.

public class MyClass
{
        private class MyElement
        {
            public string myString{ get; set; }
        }

        private class MyObj
        {
            public List<MyElement> data { get; set; }
        }

        public dynamic myMethod()
        {
            List<MyElement> myList = (some complex code here).ToList();
            var myObj = new MyObj{ data = myList };

            return myObj;
        }
}

Now I need to call such function from outside the class like this:

var c = new MyClass();
var stuff = c.myMethod();

and traverse the element of the output object but as you can see the stuff object is shaped as a dynamic (look at the return type of the function) so I don'y know the type (is private). How can I explore the array?

Upvotes: 0

Views: 3791

Answers (1)

Pavel Luzhetskiy
Pavel Luzhetskiy

Reputation: 789

I'll try to answer your question, though what you are trying to achieve is a little bit odd.

First thing: you can't access properties of dynamic object if the class of this object is private as metadata of the object is not exposed to you.

The only way is to use reflection:

var myClass = new MyClass();
var stuff = myClass.myMethod();
var dynamicType = (TypeInfo)stuff.GetType();

var dataProperty = dynamicType.GetProperty("data");
var data = (IEnumerable)dataProperty.GetValue(stuff);

var result = new List<string>();
Type itemType = null;
PropertyInfo myProperty = null;
foreach(var item in data){
    if(itemType == null){
        itemType = item.GetType();
        myProperty = itemType.GetProperty("myString");
    }

    var content = (string)myProperty.GetValue(item);
    result.Add(content);
}

Upvotes: 1

Related Questions