How to do template specialization in C#

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.

Leave a Comment