Earlier quoted context omitted.
I know of atleast one instance in C# where something like this happens. The IEnumberable .Count() extension sees if the input is actually a ICollection and uses the count on that to get the count directly, rather than iterating over it. I remember writing extension methods in C# for IEnumerable , which would of course take in an IEnumerable , but saw if the actual input was a ICollection , IList etc to optimize the o…
I'm not a heavy C# dev, but I don't understand why your first paragraph would be so: isn't that the point of implementing an interface like IEnumerable -- so that you can implement Count() in an optimized, specialized way that "gets the count directly"?
IEnumerator GetEnumerator()
method most of the real "meat" of ienumerable is in the static System.Linq.Enumerable class. You see c# doesn't have multiple inheritence or scala like traits or type classes but it does have a cool compiler hack called Extension methods(http://msdn.microsoft.com/en-us/library/vstudio/bb383977.asp...). You take a static class with static helper functions like you might make in java and you add a this keyword to the first argument then you can call it with a syntax that makes it look like it was a method on that class. For example something like
public static class Enumerable
{
public static int Count(this IEnumerable source
{
int i=0;
for(TSource t in source)
{
i++;
}
return i;
)
}
And if you use Extensions methods on an interface type you get all of the extension methods for free once you implement the minimal interface.
One of the downsides is that you can only really define it in one place and can't override it and if you want even somewhat efficient type specialized versions you need to cast.I believe in scala you can use traits in a similar manner for default implementation and specialize them for collections but traits are more complicated/powerfull feature.