When creating an array with the new keyword, we would typically expect the type to never be null. However, when using Visual Studio (VS) with nullable types enabled, the suggested type might include a nullable operator (?), indicating that the array type is nullable.
VS utilizes the var keyword, which automatically infers the most appropriate type for the variable. For reference types, var infers an annotated type. When nullable context is activated via a project file or the #nullable pragma, var will infer a nullable reference type.
This behavior stems from discussions and implementations within the .NET community. It was recognized that many instances of code required specifying the explicit type and that allowing var to infer a nullable reference type would alleviate this redundancy.
Therefore, if nullable types are enabled, VS will suggest a nullable array type when using var to declare an array with the new keyword. While it is unlikely for an array created with new to be null, this suggestion serves as a reminder of the enabled nullable context and helps maintain consistency in coding practices.
The above is the detailed content of Why Does Visual Studio's Autocomplete Suggest Nullable Arrays with `var` and `new`?. For more information, please follow other related articles on the PHP Chinese website!