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:
Here, if the compiler knows the types at compile, it will pick the most specific:
However....
will use
Foo<T>
even forTSomething=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:
Here
Bar.Foo
will always resolve to the correct override.