user47589
user47589

Reputation:

C# generic type constraints - prevent type parameters from being the same?

Consider the following generic:

class Foo<T, U> {}

Is it possible to prevent T and U from being the same type? This question is borne out of curiosity.

Upvotes: 1

Views: 306

Answers (4)

VinayC
VinayC

Reputation: 49165

As pointed out by others, you can not use Type Constraints but you can still add runtime checks using static constructors. See http://en.csharp-online.net/ECMA-334:_25.1.5_Static_constructors_in_generic_classes

Upvotes: 2

user541686
user541686

Reputation: 210352

No, there isn't such a thing. But you might want to look into other languages with template metaprogramming, such as D -- they are much more powerful, compile-time variants of generics.

Upvotes: 1

spender
spender

Reputation: 120380

http://msdn.microsoft.com/en-us/library/d5x73970%28v=vs.80%29.aspx shows us that there are 6 kinds of constraint. Equality is not included.

Upvotes: 2

Ian
Ian

Reputation: 34489

No it's not. The only options you have are listed here Constraints on Type Parameters

Upvotes: 4

Related Questions