views:

61

answers:

2

Why is this disallowed in C#? alt text

Actually I'd like to be able to write

alias Y<A, B> : X<A, B>, X<B, A>

The unification is actually desired here; if the A = B then just one method should be defined.

+2  A: 

Instead could you define your type as:

public interface Y<A> : X<A,A>
{
}
Jake Pearson
+6  A: 

The first reason that comes to mind is the following.

class Example : Y<int,int> {
 ...
}

In this case the type Y implements the same interface twice but can have differing implementations of the same method. This creates an unresolvable ambiguity in the compiler for the method Tx in both implementation and calling.

For example take the following problem.

class OtherExample<A,B> : Y<A,B> {
  B Tx(A x) { 
    Console.WriteLine("Top method in the file");
    return default(B); 
  }
  A Tx(B x) { 
    Console.WriteLine("Bottom method in the file");
    return default(A);
  }
}

If you ignore the unification error this is a legal implementation of Y<A,B>. Now imagine the user did the following

var v1 = new OtherExample<int,int>();
v1.Tx(42);

What exactly would happen in this scenario? How would the compiler, or the CLR for that matter, be able to resolve the ambiguity? You'd have identically named methods with identical signatures.

JaredPar
A simple compile-time error would do.
Bent Rasmussen
- The philosophy being that if you make a non-sensical instantiation you asked for it but that is better than disallowing a useful pattern. That is: don't throw away the tool just because it can be abused: the abuse can be statically checked and denied.
Bent Rasmussen