for example, I have a (non-static) class Foo<T>
I would like to add a method bar() for Foo, however this method should only work for Foo<int>.
Because we cannot overload type constraints,
Do I have to create an extension method in a separate static class bar(this Foo<int> myFoo)?
Basically, yes. C# (and the CLR in general) does not support template specialization known from C++.
Type parameters are meant to be used when your class'es implementation doesn't care about the actual type at all.
As an alternative, add a runtime check to make sure the method is only being called on typeof(T) == typeof(int).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With