Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange C# behavior of a property with a nullable type

A simple example:

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'
}

Why does A work, but B fails to compile?

Is it a bug? If not, where this different behavior is described/specified?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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?.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading