0

Working with VS2022 and .NET 8 with <Nullable>Enabled</Nullable> for my project.

I encounter null pointer exception at run time with the following code:

string[] arrayOfString = new string[2];
Console.WriteLine(String.Join(',', arrayOfString.Select(s => s ?? "null")))
arrayOfString[0].ToString();

The array is created with 2 string where the default value for string which is null.

I fixed the issue with the following initialization:

string?[] arrayOfString = new string[2];

However, I was expecting a warning at compile time (an error at compilation in my case as I set <TreatWarningsAsErrors>True</TreatWarningsAsErrors>) with Nullable enabled? Is it an expected behavior or a bug?

13
  • 3
    Side note: s => s ?? null is redundant and can be dropped: "if s is null, let it be null" Commented May 8, 2024 at 8:02
  • 2
    Cannot reproduce Commented May 8, 2024 at 8:04
  • "I was expecting a compilation error" Nullable violations cause warning, not errors. But i agree that there could be a warning. Commented May 8, 2024 at 8:20
  • 2
    "Arrays and structs that contain reference types are known pitfalls in nullable references and the static analysis that determines null safety. In both situations, a non-nullable reference might be initialized to null, without generating warnings." from docu here Commented May 8, 2024 at 8:30
  • @Ralf: "known pitfalls in nullable references and the static analysis that determines null safety" could also be called "known bugs". It was just too much effort to implement it i would say. Commented May 8, 2024 at 8:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.