• Feeds

    Subscribe in a reader

  • Ads

More on Generic Algorithms in C#

Eric Gunnerson presents an interesting pattern that happens to get around the problems with generics, operators, and primitive types that I mention in this rant. The implementation he presents is quite clever.

His code demonstrates a property of generic methods of which I was not previously aware: namely, you can override generic methods with non-generic methods, provided the compiler has enough information to close the type of the generic method which you are overriding. From Eric's example (code's his, comments are mine):

//The abstract generic root class
public abstract class Calculator
{
    public abstract T Add(T a, T b);
}

//The concrete non-generic inheritor
public class Calculator: Calculator{
   //Note that this signature matches the signature
   //of the closed form of the abstract method inherited
   //from the parent class, even though the overriding
   //method is not itself generic.

   public override int Add(int a, int b)
   {
            return a + b;
   }
}

As Eric points out, this will never be as fast as something like this:

public T Add(T a, Tb) where T:#IPromiseThatWhatEverIPutInHereWillBeAddableJustTrustMe#

due to that his example has the overhead of an additional vtable dispatch. However, his example has the distinct advantage of actually working, since the concept between the # marks is at present inexpressable in C# (or the CLR, for that matter).

The ability to do this seems a little strange to me, because it sort of implies that generic params are not a true component of a method signature. Apparently, they're not used to do vtable dispatch, because his example is showing that the generic T Add() and the non-generic int Add(int) are actually occupying the same slot in the vtable. Or has the CLR's vtable dispatch algorithm become smart enough to close the generic and then do the dispatch against that result, regardless of whether the target method is actually generic or not. Eric's example seems to imply the latter. I think the MSR whitepaper touched on this a little bit, but if I remember correctly, this fell under the section of “forthcoming publication“...

Anyway, I think that it's very important that C# generics be able to support some sort of generic algorithm capability. Even if that support comes in the somewhat roundabout way that Eric presented, it's better than nothing. Yes, I love generic collection type and will sing the praises of the Whidbey implementation if for no other reason than that, but you can do some very, very cool things with generic algorithms...

 

#1 news on 4.18.2007 at 5:48 AM

intext:"Please enter the verification code from the image above into the entry area before clicking on Send comment"

#2 news on 4.18.2007 at 5:49 AM

intext:"Please enter the verification code from the image above into the entry area before clicking on Send comment"