How to access count property of a dynamic type in C# 4.0?

You'll need to explicitly call Enumerable.Count().

IEnumerable<string> segments =
  from x in new List<string> { "one", "two" } select x;

Console.WriteLine(segments.Count());  // works

dynamic dSegments = segments;

// Console.WriteLine(dSegments.Count());  // fails

Console.WriteLine(Enumerable.Count(dSegments));  // works

See Extension method and dynamic object in c# for a discussion of why extension methods aren't supported by dynamic typing.

(The "d" prefix is just for the example code - please do not use Hungarian notation!)

Update: Personally I'd go with @Magnus's answer of using if (!Segments.Any()) and return IEnumerable<dynamic>.


The IEnumerable<T> that's returned from that method doesn't have a Count property, so I don't know what you're talking about. Maybe you forgot to write ToList() on the end to reify it into a list, or you meant to call the Count() method on IEnumerable<T>?


Count() needs to enumerate to complete collection, you probably want:

if (!Segments.Any()) 
{
}

And your function should return IEnumerable<object> instead of dynamic