9

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?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
Mikael Koskinen
  • 12,306
  • 5
  • 48
  • 63
  • possible duplicate of [Extension method and dynamic object in c#](http://stackoverflow.com/questions/5311465/extension-method-and-dynamic-object-in-c-sharp) – nawfal Jul 19 '14 at 20:59

2 Answers2

6

Seems that extension methods do not work on dynamic objects (see Jon' answer). However, you can call those directly as static methods:

var count = Enumerable.Count(data); // works
Community
  • 1
  • 1
Alexander Tsvetkov
  • 1,649
  • 14
  • 24
6

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'

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263