11

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?

Community
  • 1
  • 1
user664939
  • 1,977
  • 2
  • 20
  • 35
  • 1
    You can always throw a `new ShouldBeCompileTimeError()` in the constructor. :-) – foson Nov 08 '11 at 20:28
  • 1
    probably because it doesn't make sense, they are generics, something that shouldn't be "constrained" by types. – GriffinHeart Nov 08 '11 at 20:30
  • Out of curiosity, what are the negative consequence if this constraint is not met? A mapping between objects from the same set is a very common requirement. – Dan Bryant Nov 08 '11 at 20:34
  • @DanBryant: 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. This is not a serious negative consequence, which is why it's a question of curiosity. My goal for the question is that it would teach me something about how the language works rather than help me index more conveniently. – user664939 Nov 08 '11 at 20:40
  • @user664939, Actually, that is an interesting case I hadn't considered; allowing two generic type parameters to define distinct method overloads. The compiler actually allows this to compile, so I'm curious; does it arbitrarily pick one of the methods to call? – Dan Bryant Nov 08 '11 at 20:50
  • @DanBryant: I edited some of this conversation into the question. Please edit it if you feel I misquoted you. Thanks for the interest. – user664939 Nov 08 '11 at 21:00
  • @DanBryant: I'm not sure what you mean by "arbitrarily pick one of the methods to call". Any given variable is of a specific type - T1 or T2 - and that's known at compile time regardless of whether T1 and T2 are the same are not. I fail to see where there is a conflict. – Dave C Nov 08 '11 at 21:07
  • 1
    @user664939, I dug a bit deeper and the compiler allows you to compile a class with matching overloads, but it fails when you try to call the method (with an ambiguous invocation error.) It appears that it allows you to define a generic specialization that compiles and can be referenced, but the C# compiler is incapable of emitting the code to call the method (it's possible to emit the IL to call one of the two methods, but the compiler can't tell the difference when T1 == T2.) – Dan Bryant Nov 08 '11 at 21:17
  • @Dave C, when you're calling a public method from outside the class and T1==T2, the compiler has no way of knowing which overload you're calling. You could use this for private methods (where T1 and T2 are still distinguished), but it breaks down at the public interface. The public interface is still there, but the ambiguous overloaded methods become unusable from C#. – Dan Bryant Nov 08 '11 at 21:18
  • 1
    @DaveC: If you have `class Map {void Remove(T1 t){...} void Remove(T2 t){...}`, which one will be run when you call `new Map().Remove("contrived example")`? – user664939 Nov 08 '11 at 21:21
  • Aha! I see what you mean now. Attempting to call the method results in an ambiguous reference, which is a compile-time error. – Dave C Nov 08 '11 at 21:29
  • @DaveC: Ah, you are correct. So the compiler prevents the ambiguous reference, therefore preventing an invalid use of the two generics, therefore upholding the constraint. Very interesting. The error text: `The call is ambiguous between the following methods or properties: BidirectionalMap.this[T]' and 'BidirectionalMap.this[K]'" – user664939 Nov 08 '11 at 21:40

6 Answers6

6

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

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
  • Excellent root answer! Error text: `The call is ambiguous between the following methods or properties: BidirectionalMap.this[T]' and 'BidirectionalMap.this[K]'" – user664939 Nov 08 '11 at 21:43
1

The inequality wouldn't help the compiler to catch errors. When you specify constraints on type parameters, you are telling the compiler that variables of this type will always support a certain interface or will behave in certain ways. Each of those allows the compiler to validate something more like "this method will be present so it can be called on T".

The inequality of type parameters would be more like validating that method arguments are not null. It is part of the logic of the program, not its type safety.

Kevin Coulombe
  • 1,517
  • 1
  • 17
  • 35
0

Type constraints seem like a misnomer. While they do contrain what the type parameter is, the purpose is to let the compiler know what operations are available to the type.
If you wanted to, you can have a constraint where T1 and T2 both derive from seperate concrete base classes, but I don't think that's quite what you want.

foson
  • 10,037
  • 2
  • 35
  • 53
0

I'm not entirely sure why this would be a desirable compile time check. It would be possible to essentially by-pass the condition by boxing either the key or the value, thereby rendering the compile-time check useless.

Some consideration needs to be made to determine... what errors am I trying to prevent?

If you are simply stopping a lazy co-worker from not reading the documentation, then add a Debug only check and throw an exception. This way the check can be removed for release code e.g.

#if Debug

if (T1 is T2 || T2 is T1)
{
    throw new ArguementException(...);
}

#endif

If you are attempting to prevent a malevolent person from using your library in an unintended way, then perhaps a runtime check is needed, otherwise it would be easy to box the key or value.

TK.
  • 46,577
  • 46
  • 119
  • 147
  • You can also put this check in the static constructor of the generic type, so it will only run once. (Your check won't compile, by the way, because the left side of the `is` operator takes an object reference, not a type name. You want `if (typeof(T1) == typeof(t2)`) – phoog Nov 08 '11 at 22:10
0

No, you cannot use equality (or inequality) as a constraint. Simply put, equality is not a constraint, but a condition. You should test for a condition such as equality or inequality of types in the constructor and throw an appropriate exception.

IAbstract
  • 19,551
  • 15
  • 98
  • 146
-1

There is no effective way to do this without imposing any other restrictions on the types themselves. As someone else noted, you could make constraints that the two types derived from two different base classes, but that's probably not very good from a design standpoint.

Edited to add: the reason this is not implemented is most likely because nobody at Microsoft ever considered something like this to be necessary to enforce at compile time, unlike the other constraints which have to do with how you're actually able to use variables of the specified types. And as some commenters have pointed out, you can certainly enforce this at runtime.

Dave C
  • 429
  • 3
  • 9