colinfang
colinfang

Reputation: 21707

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

Upvotes: 3

Views: 62

Answers (1)

usr
usr

Reputation: 171178

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

Upvotes: 3

Related Questions