If I have the C# 8 code:
class Foo {}
And later:
#nullable enable
var bar = new Foo();
Then the type of bar is Foo?. This seems clearly incorrect, as a new expression can't return null. Why would bar be a nullable reference? I even looked up the Nullable Reference Type Specification, and found the following:
Expressions that are never null
The null state of the following expression forms is always "not null":
- ...
newexpressions (object, delegate, anonymous object and array creation expressions)- ...
And also:
Type inference for var
The type inferred for local variables declared with var is informed by the null state of the initializing expression.
var x = E;If the type of
Eis a nullable reference typeC?and the null state ofEis "not null" then the type inferred forxisC. Otherwise, the inferred type is the type ofE.The nullability of the type inferred for
xis determined as described above, based on the annotation context of thevar, just as if the type had been given explicitly in that position.
So based on everything I can find in the spec, bar in my very simple example should be of type Foo, not type Foo?. What am I missing?