Search code examples
c#classtypestype-constraints

C# - Is there a way to constrain two type parameters to be necessarily different?


I'm building a MyClass<T1, T2> : IEnumerable<Tuple<T1, T2>> class, but for it to make any kind of sense in the context of my application I need to ensure that T1 != T2.

Is there a proper way to constrain T1 and T2 so that they aren't the same type?


Solution

  • If you know what types they should be, you can use the where type constraint:

    class MyClass<T1, T2> : IEnumerable<Tuple<T1, T2>>
        where T1 : MyClass1
        where T2 : MyClass2
    

    But there is no way to allow them to be any class, but enforce that they are not equal. You would have to throw an exception in the constructor maybe:

    if (typeof(T1) == typeof(T2)) {
        throw new Exception("Types must not be the same.");
    }