4 ms·
(I'm not a c# expert and I may be wrong) IEnumerable really only requires a IEnumerator GetEnumerator() method most of the real "meat" of ienumerable is in th
by rat87 13y ago
(I'm not a c# expert and I may be wrong)
IEnumerable really only requires a
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.aspx 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<TSource>(this IEnumerable<TSource> 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.
- pjmlp 13y agoThis is not a compiler hack, there are quite a few languages out there that support this concept. As for your Scala remark, extension methods in Scala are done via implicits.
- rat87 13y agoI didn't mean hack in a derogatory way, I think its a fairly elegant solution in many ways just that to my knowledge it doesn't really change the static/dynamic type and is just a simple compiler transformation. I should have mentioned that I know even less about scala then c#. I/m not quite sure how implicits are implemented/optimized but I'm pretty sure you can have inheritence/overiding traits as implicits.