Why can I get a compilation error when creating this error?

This code works:

class Example { public Int32 Int32 { get { return Int32.Parse("3"); } } } 

This code does not compile:

 class Example { public Int32? Int32 { get { return Int32.Parse("3"); } } } 

CS1061 'int?' contains no definition for "Parse" and no extension method "Parse" that takes the first argument of type "int?" (you did not specify a usage directive or assembly reference?)


My example may look silly, but it makes sense if you use enum view like

 public Choice? Choice { get { return Choice.One; } } 
+5
source share
2 answers

If the property type name is the same as the property name, this is a special case covered by the specification:

7.6.4.1 Identical simple names and type names
In member access of form EI , if E is a single identifier, and if the value of E as a simple name (ยง7.6.2) is a constant, field, property, local variable, or parameter with the same type as the value of E as a type name (ยง 3.8), then both possible values โ€‹โ€‹of E are allowed. Two possible values โ€‹โ€‹of EI never ambiguous, since I must be a member of type E in both cases. In other words, the rule simply allows access to static members and nested types of E , where a compile-time error occurred otherwise.

So, in your first fragment of the simplest name Int32 can refer to the Int32 property, as well as to the Int32 type.

In the second fragment, this rule is not applied, and the simple name Int32 refers only to the property.

+5
source

In the second example, Int32 refers to the Int32 property of not dialing System.Int32 . And since the Int32 property is of type System.Nullable(System.Int32) , it does not have a parsing method.

You will need to write

 public Int32? Int32 { get { return System.Int32.Parse("3"); } } 
+7
source

All Articles