3

I can create a generic class and use "where" statement like:

public class TestClass<T> where T: IDisposable
{
    .... 
}

To be sure that the type "T" is implement the interface 'IDisposable'.

Is there some way to create generic class with 2 types that constrain the types to be different from one another like:

public class TestClass<T,K> where T!=K
{
    .... 
}

Thanks

user436862
  • 867
  • 2
  • 15
  • 32
  • 4
    No. Question is - why do you want that? – Konrad Kokosa Nov 12 '14 at 13:23
  • It's not possible. Look at this question: http://stackoverflow.com/questions/10642751/excluding-types-in-the-generic-constraints-possible – Paweł Reszka Nov 12 '14 at 13:24
  • 1
    What's the problem with T being equal to K? – huysentruitw Nov 12 '14 at 13:27
  • I want to create a Bijection collection. I want to ensure that the value and key are not the same type for be able to user the [] operator without ambiguos but in complination and not in runtime(like checking types in ctor and throw exception in case that they are the same). – user436862 Nov 12 '14 at 13:31
  • See [Constraints on Type Parameters](http://msdn.microsoft.com/en-us/library/d5x73970.aspx). – Evil Dog Pie Nov 12 '14 at 13:32
  • 1
    Not get it - why for the same type of T and K, "the [] operator" would be ambiguos? – Konrad Kokosa Nov 12 '14 at 13:35
  • Using the `[]` notation is (IMO) just syntactic candy. could you solve the problem by using unambiguous methods or properties? – Evil Dog Pie Nov 12 '14 at 13:38
  • This sounds like an aspect of the program. Perhaps you can consider Aspect Oriented Programming to provide this constraint at compile-time. [PostSharp][1] should provide this capability. [1]: http://www.postsharp.net/architecture/custom-architectural-constraints – Scott Nimrod Nov 12 '14 at 13:39
  • Because i have 2 implemention of this operator(Key to value and value to key) – user436862 Nov 12 '14 at 13:48
  • In the case T==K you will get compilation error `The call is ambiguous between the following methods or properties`. Isn't it that you need? – neleus Nov 12 '14 at 13:50

0 Answers0