2

I am initializing dynamic with ExpandoObject and adding some items to it.

        dynamic dy = new System.Dynamic.ExpandoObject();
        dy.Property2 = new List<string>();
        dy.Property2.Add("Two");
        dy.Property2.Insert(0, "Zero");
        var coll1 = (List<string>)dy.Property2;
        var element = coll1.ElementAt(0);

above code works fine. but exception is thrown if replace last two statement with code mention below

        var data = dy.Property2.ElementAt(0);

exception is 'System.Collections.Generic.List' does not contain a definition for 'ElementAt'

1 Answer 1

5

And it's absolutely right - List<T> doesn't have an ElementAt method. It only works in your original code because it's an extension method on IEnumerable<T>. Dynamic typing doesn't let you call extension methods using the "special" syntax - but you can call it as a normal static method call:

var data = Enumerable.ElementAt(dy.Property2, 0);
Sign up to request clarification or add additional context in comments.

3 Comments

On MSDN for dynamic its written " The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object" Can you please explain, need to understand ??
@slashshogdhe: Not in a comment thread, no. There's a huge amount to be said about dynamic (I wrote a whole chapter on it in C# in Depth) - it's really not appropriate to go into details within comments.
Placed a question on stackoverflow, please help now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.