Consider this code:
static void Main(string[] args)
{
var ints=new List<int> {10,11,22};
Something(ints);//Output:Count is:3
Something(new int[10]); //'System.Array' does not contain
// a definition for 'Count'
Console.ReadLine();
}
static void Something(ICollection collection)
{
dynamic dynamic = collection;
Console.WriteLine("Count is:{0}", dynamic.Count);
}
When pass a List all thing is ok. But when pass array and convert to dynamic i get this error:'System.Array' does not contain a definition for 'Count'
.
I know what is my solution but i want to know why compiler has a this behaviors?
Best Answer
Now that we can understand why dynamic.Count is trying to call System.Array.Count. However, it's still unclear why Array.Count is not defined when Array implements System.Collections.ICollection which has a Count method. Array does in fact implement ICollection correctly, and it does have a Count method. However, consumers of Array.Count do not have permission to access the Count property without explicitly casting the Array to an ICollection. Array.Count is implemented with a pattern known as explicit interface implementation where Array.Count is explicitly implemented for ICollection. And you may only access the count method by casting your variable to an ICollection with this pattern. This is reflected in the docs for Array. Look for the "Explicit Interface Implementations" section.