Why does A work, but B fails to compile?
Is it a bug? If not, where this different behavior is described/specified?
enum ControlType { Foo }
class A
{
public ControlType ControlType = ControlType.Foo;
}
class B
{
public ControlType? ControlType = ControlType.Foo; // <-- error CS0236: A field initializer cannot reference the non-static field, method, or property 'B.ControlType'
}
The difference is whether the situation ends up meeting the requirements of section 12.8.7.2 of the C# spec - "Identical simple names and type names".
In a member access of the form
E.I, ifEis a single identifier, and if the meaning ofEas a simple_name (§12.8.4) is a constant, field, property, local variable, or parameter with the same type as the meaning ofEas a type_name (§7.8.1), then both possible meanings ofEare permitted. The member lookup ofE.Iis never ambiguous, sinceIshall necessarily be a member of the typeEin both cases. In other words, the rule simply permits access to the static members and nested types ofEwhere a compile-time error would otherwise have occurred.
In your case A, ControlType.Foo looks up ControlType, finds that it's a property with the same type as E (ControlType) and so allows the member lookup of Foo both as a static member of the type and as an member (via effectively accessing the ControlType property).
In your case B, ControlType.Foo looks up ControlType, finds that it's a property with a different type to E (it's ControlType? this time) so the member lookup proceeds only with the members of ControlType?.
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