C# – How to do template specialization in C#

cpartial-specialization

How would you do specialization in C#?

I'll pose a problem. You have a template type, you have no idea what it is. But you do know if it's derived from XYZ you want to call .alternativeFunc(). A great way is to call a specialized function or class and have normalCall return .normalFunc() while have the other specialization on any derived type of XYZ to call .alternativeFunc(). How would this be done in C#?

Best Answer

In C#, the closest to specialization is to use a more-specific overload; however, this is brittle, and doesn't cover every possible usage. For example:

void Foo<T>(T value) {Console.WriteLine("General method");}
void Foo(Bar value) {Console.WriteLine("Specialized method");}

Here, if the compiler knows the types at compile, it will pick the most specific:

Bar bar = new Bar();
Foo(bar); // uses the specialized method

However....

void Test<TSomething>(TSomething value) {
    Foo(value);
}

will use Foo<T> even for TSomething=Bar, as this is burned in at compile-time.

One other approach is to use type-testing within a generic method - however, this is usually a poor idea, and isn't recommended.

Basically, C# just doesn't want you to work with specializations, except for polymorphism:

class SomeBase { public virtual void Foo() {...}}
class Bar : SomeBase { public override void Foo() {...}}

Here Bar.Foo will always resolve to the correct override.