I am trying to write a method that accepts as a parameter any IEnumerable<T>
; and call it from code where T
will not be known until runtime.
I could write it as a generic method and then invoke it with reflection when I want to use it, but for a variety of reasons I decided to use type dynamic. However when I passed in a strongly typed collection output from an Entity Framework function import (a System.Data.Objects.ObjectQuery<T>
) and tried to access the Count() method, it threw an exception to the effect that System.Data.Objects.ObjectQuery<T>
didn't have a Count() method, which is not the case.
I've worked around this by limiting my interaction with the object to a foreach statement, thus making the compiler figure out how to enumerate it, so it's not a problem. I'm more interested in understanding why I can't do this. My guess is that it's either that Count() is a method on a base class or interface and therefore not accessible for some reason, or that the compiler usually translates calls to Count() to Count<T>
during compilation and can't do so in this case? Help appreciated.
Edit: I feel like it's probably the case that the compiler is not translating the non-generic Count()
into a generic Count<T>
. When you call Count()
on an IEnumerable<T>.Count()
you are actually calling Count<T>()
, it's just syntactic sugar that the compiler takes care of. I think it's probably not making the same translation of Count()
to Count<T>()
at runtime. It would be nice to get confirmation of this because this is a pretty annoying limitation of use of generics with type dynamic if so.
Also edited to add code:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException was unhandled by user code HResult=-2146233088 Message='System.Data.Objects.ObjectResult' does not contain a definition for 'Count' Source=Anonymously Hosted DynamicMethods Assembly StackTrace: at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at MyNamespace.HtmlHelpers.RenderTable(Object list, String id, String cssClass) in [snip]
And an example of the code that throws the exception:
public static MvcHtmlString RenderTable(dynamic list, string id, string cssClass)
{
int x = list.Count();
........
........
}