After encountering some problems with Massive today, I decided to create a simple test program to illustrate the problem. I wonder, what's the mistake I'm doing in this code:
var list = new List<string>
{
"Hey"
};
dynamic data = list.Select(x => x);
var count = data.Count();
The last line throws an error: 'object' does not contain a definition for 'Count'
Why is the "data" treated as an object? Does this problem occur because I'm calling an extension method?
The following code works:
var list = new List<string>
{
"Hey"
};
dynamic data = list.Select(x => x);
foreach (var s in data)
{
}
Why in this case "data" is correctly treated as IEnumerable?
Yes, that's because Count()
is an extension method.
extension methods aren't supported by dynamic typing in the form of extension methods, i.e. called as if they were instance methods. (source)
foreach (var s in data)
works, because data
has to implements IEnumerable
to be a foreach
source - there is (IEnumerable)data
conversion performed during execution.
You can see that mechanish when trying to do following:
dynamic t = 1;
foreach (var i in t)
Console.WriteLine(i.ToString());
There is an exception thrown at runtime: Cannot implicitly convert type 'int' to 'System.Collections.IEnumerable'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With