Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A generic class with two non-equal (unique) types

Is it possible to implement a class constrained to two unique generic parameters?

If it is not, is that because it is unimplemented or because it would be impossible given the language structure (inheritance)?

I would like something of the form:

class BidirectionalMap<T1,T2> where T1 != T2
{
  ...
}

I am implementing a Bidirectional dictionary. This is mostly a question of curiosity, not of need.


Paraphrased from the comments:

  1. Dan: "What are the negative consequence if this constraint is not met?"

  2. Me: "Then the user could index with map[t1] and map[t2]. If they were the same type, there would be no distinction and it wouldn't make any sense."

  3. Dan: The compiler actually allows [two generic type parameters to define distinct method overloads], so I'm curious; does it arbitrarily pick one of the methods to call?

like image 675
user664939 Avatar asked Nov 08 '11 20:11

user664939


1 Answers

Expanding on the example to highlight the problem:

public class BidirectionalMap<T1,T2>
{
    public void Remove(T1 item) {}
    public void Remove(T2 item) {}

    public static void Test()
    {
        //This line compiles
        var possiblyBad = new BidirectionalMap<string, string>();

        //This causes the compiler to fail with an ambiguous invocation
        possiblyBad.Remove("Something");
    }
}

So the answer is that, even though you can't specify the constraint T1 != T2, it doesn't matter, because the compiler will fail as soon as you try to do something that would violate the implicit constraint. It still catches the failure at compile time, so you can use these overloads with impunity. It's a bit odd, as you can create an instance of the map (and could even write IL code that manipulates the map appropriately), but the C# compiler won't let you wreak havoc by arbitrarily resolving ambiguous overloads.


One side note is that this kind of overloading could cause some odd behaviors if you're not careful. If you have a BidirectionalMap<Animal, Cat> and Cat : Animal, consider what will happen with this code:

Animal animal = new Cat();
map.Remove(animal);

This will call the overload that takes Animal, so it will try to remove a key, even though you might have intended to remove the value Cat. This is a somewhat artificial case, but it's enough to warrant caution when very different behaviors occur as a result of method overloading. In such cases, it's probably easier to read and maintain if you just give the methods different names, reflecting their different behaviors (RemoveKey and RemoveValue, let's say.)

like image 112
Dan Bryant Avatar answered Sep 22 '22 15:09

Dan Bryant