Skip to content

new() not respecting nullable struct #57777

@CyrusNajmabadi

Description

@CyrusNajmabadi

Discussed in #57760

Originally posted by AlexanderHawliczek November 15, 2021
Refactoring showed some odd behavior.
Refactoring was done

var a = new int?();
-> Use explicit type
int? c = new int?();
-> Use target-typed new Style Rule IDE 0090
int? d = new();
This caused a change in actual value as new() creates a new Int32 not an Int32?.

var a = new int?();
int? b = null;
int? c = new int?();
int? d = new();
Console.WriteLine(nameof(a) + " - has value " + a.HasValue + " - Value " + a);
Console.WriteLine(nameof(b) + " - has value " + b.HasValue + " - Value " + b);
Console.WriteLine(nameof(c) + " - has value " + c.HasValue + " - Value " + c);
Console.WriteLine(nameof(d) + " - has value " + d.HasValue + " - Value " + d);

Output
a - has value False - Value
b - has value False - Value
c - has value False - Value
d - has value True - Value 0

Used .Net 5 & 6 VS Studio 2019 & 2022

Is this a bug or a feature?
Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions