int[] arr = new int[5];
Console.WriteLine(arr.Count.ToString());//Compiler Error
Console.WriteLine(((ICollection)arr).Count.ToString());//works print 5
Console.WriteLine(arr.Length.ToString());//print 5
Do you have an explanation for that?
Arrays have .Length, not .Count.
But this is available (as an explicit interface implementation) on ICollection etc.
Essentially, the same as:
Bar
doesn't have public aFoo
property - but it is available if you cast toIFoo
:While
System.Array
implement theICollection
interface it doesn't directly expose theCount
property. You can see the explicit implementation ofICollection.Count
in the MSDN documentation here.The same applies to
IList.Item
.Take look at this Blog entry for more details on explicit and implicit interface implementation: Implicit and Explicit Interface Implementations
Whilst this doesn't answer your question directly, if you are using .NET 3.5 you can include the namespace;
which will then allow you to use a Count() method, similar to when casting your int array as an ICollection.
You also then have a whole host of nice functions you can use in Linq too :)