Here is my code so far:
//TODO: Look for a way of handling ICollection<T>
if (value is ICollection)
{
return CreateResult(validationContext, ((ICollection)value).Count);
}
if (value is IEnumerable)
{
var enumerator = ((IEnumerable)value).GetEnumerator();
try
{
var count = 0;
while (enumerator.MoveNext())
count++;
return CreateResult(validationContext, count);
}
finally
{
if (enumerator is IDisposable)
((IDisposable)enumerator).Dispose();
}
}
Is there a good way of getting the Count out of ICollection<T> without resorting to iterating over the collection?
Reflection would be the way to go, but keep in mind that most of the Collections in the FCL inherit from both
ICollection<T>andICollectionSo code like this works:True is output for both. This works for most, if not all, collections in the FCL. If you needed it to work against custom collections, or collections that don’t implement ICollection, then reflection is the only way.
Sidenote: Arrays also implicitly implement ICollection, IList and IEnumerable (the CLR actually generates an array that inherits from the generic versions of those classes in addition to the non-generic at runtime), so your above code would work with arrays as well.