Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it possible to refer to enum values when a field is named identically to the enum type, but not when the field type is made nullable?

Tags:

c#

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'
}
like image 881
TN. Avatar asked Nov 27 '25 14:11

TN.


1 Answers

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, if E is a single identifier, and if the meaning of E as a simple_name (§12.8.4) is a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type_name (§7.8.1), then both possible meanings of E are permitted. The member lookup of E.I is never ambiguous, since I shall necessarily be a member of the type E in both cases. In other words, the rule simply permits access to the static members and nested types of E where 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?.

like image 171
Jon Skeet Avatar answered Nov 30 '25 04:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!