I wrote this extension method :
public static class A
{
public static IEnumerable<dynamic> AsDynamic<T>(this IEnumerable<T> f)
{
foreach (var element in f)
{
yield return (dynamic) element;
}
}
}
And tested it :
List<int> l = new List<int>(){1,2,3};
Console.WriteLine ( l.AsDynamic().GetType());
However the output is : typeof (IEnumerable<Object>)
-
Why it is not
typeof (IEnumerable<dynamic>)? -
How can I make it to be like it ?
I think that you have a misunderstanding of what
dynamicmeans. Essentially, when you tell the compiler that an object’s type isdynamic, you “promise” that the object at runtime will support whatever methods or properties that you invoke, in exchange for the compiler not complaining at compile time. You also promise that you will face the consequences if you break your promise.When you say that an object is
dynamic, the compiler cannot make assumptions about the type, so it usesobject, knowing that anything can be stored asobject. When you make anIEnumerable<dynamic>, it becomesIEnumerable<object>, with one significant difference: you can call any method on its elements, and the compiler will not say a word:Since
original.AsDynamic()gives a sequence ofdynamicobjects, the compiler does not complain about your call toSomeUnsupportedMethod. If the method is indeed not supported at runtime, the program will crash; if the method is actually supported by elements ofSomeType, there would be no crash, and the method will be invoked.That’s all the
dynamicwill do for you; statically, the “placeholder” will remainobject, andtypeofwill tell you as much. But the exact capabilities of the object (its methods and properties) will not be examined until runtime.