Let's say I've got a special collection where an item is both a key and a value such that two items are partnered in a unique 1:1 relationship. Say I want to make this collection generic.
Here's part of the interface I'd like to use to make this partnered relationship possible:
This works well and good so long as T and V do not have the same type. The default accessor works as planned. If, however T and V have the same type, an ambiguity is created as to which default property to use. The same would be the case for any overloaded methods one taking a parameter of type T, the other V. This would not be the case with other methods, such as Add in this case.
I do get a compile time warning, as expected, but only after I've made the declaration. For example, say I have a class that implements the above interface called PartnerCollection<T, V>.
This makes sense...sort of. It's good to see that you can't create Generics remain mostly internally consistent, disallowing an ambiguous method. It's a little disturbing that the only way to know this is when you use the method. The only advantage I see here is that you still get a compile time error instead of a run time error.
My Question: Is there a way to know whether there will be an ambiguity at declaration instead of only when you use a potentially ambiguous method? In other words, is there a way I can put a constraint on a generic class such that T and V cannot have the same type?
Here's part of the interface I'd like to use to make this partnered relationship possible:
C#:
public interface IPartnerCollection<T, V>
{
T this[V item] { get; set; }
V this[T item] { get; set; }
void Add(T, V);
// ...
}
I do get a compile time warning, as expected, but only after I've made the declaration. For example, say I have a class that implements the above interface called PartnerCollection<T, V>.
C#:
//no compile errors
PartnerCollection<string, int> good = new PartnerCollection<string, int>();
good.Add("YO", 55);
Console.WriteLine("The partner of 55 is: " + good[55]);
Console.WriteLine("The partner of YO is: " + good["YO"].ToString());
//compile errors for ambiguous method call
PartnerCollection<string, string> bad = new PartnerCollection<string, string>(); //no error at declaration
bad.Add("YO", "55"); //no error when using an unambiguous method
Console.WriteLine("The partner of 55 is: " + bad["55"]); //error ONLY when you USE an ambiguous method
Console.WriteLine("The partner of YO is: " + bad["YO"]);
My Question: Is there a way to know whether there will be an ambiguity at declaration instead of only when you use a potentially ambiguous method? In other words, is there a way I can put a constraint on a generic class such that T and V cannot have the same type?
Last edited: