If I try to define the following Pair<A, B>
class in C#, I get a compiler error.
public class Pair<A, B>
{
public Pair(A a, B b)
{
this.A = a;
this.B = b;
}
public A A { get; }
public B B { get; }
}
The compiler error is:
error CS0102: The type 'Pair<A, B>' already contains a definition for 'A' error CS0102: The type 'Pair<A, B>' already contains a definition for 'B'
Where are the conflicting definitions?
Usually, one can define a property with the same name as its type, e.g.:
public Guid Guid { get; }
public Uri Uri { get; }
Why is the compiler complaining about the names A
and B
?
It's specified in the "Class members" section in the C# standard. In the current draft-v6 branch:
The name of a type parameter in the type_parameter_list of a class declaration shall differ from the names of all other type parameters in the same type_parameter_list and shall differ from the name of the class and the names of all members of the class.
In other words, you can't get a type parameter the same name as another type parameter or a class member. Here, you have a type parameter called A
and a property called A
.
The fact that the type of the property is also A
is irrelevant; this code gives the same error:
class Broken<T>
{
public string T { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With