Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dynamic and working with IEnumerable collections

Tags:

c#

dynamic

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?

like image 372
Mikael Koskinen Avatar asked Apr 05 '13 10:04

Mikael Koskinen


Video Answer


1 Answers

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'

like image 192
MarcinJuraszek Avatar answered Oct 01 '22 20:10

MarcinJuraszek