Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to create extension methods if I want to add type constrained (T=int) method onto a generic (T) class?

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)?

like image 514
colinfang Avatar asked Jan 26 '26 01:01

colinfang


1 Answers

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).

like image 178
usr Avatar answered Jan 27 '26 13:01

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!