Below code work perfectly fine unless I change GetCount parameter type from ICollection to dynamic - it throws RuntimrBinderException Why at runtime Count property is not available ?
static void Main(string[] args)
{
var list = new int[] { 1, 2, 3 };
var x = GetCount(list);
Console.WriteLine(x);
}
private static int GetCount(ICollection array) /*changing array type to dynamic fails at runtime*/
{
return array.Count;
}
The reason this fails is because in arrays, although they implement
ICollection,Countis implemented explicitly. Explicitly implemented members can only be invoked through the interface typed reference.Consider the following:
And now:
In your case, when the argument is typed
ICollection,Countis a valid invocation, but whendynamicis used, the argument isn't implicitly converted toICollection, it remains aint[]andCountis simply not invocable through that reference.