Raheel Khan
Raheel Khan

Reputation: 14787

Why does a literal string assignment using the "var" keyword declare the variable as nullable?

I am targeting .NET 8 and wonder why declarations using the var keyword result in nullable types.

You can see this in these sets of declarations:

string a = "";
string b = string.Empty;
string filename = $@"notepad.exe";
string path = Environment.GetFolderPath(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None);
FileInfo file = new FileInfo(Path.Combine(path, filename));
var a = "";
var b = string.Empty;
var filename = $@"notepad.exe";
var path = Environment.GetFolderPath(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None);
var file = new FileInfo(Path.Combine(path, filename));

There is nothing about the assignments that implies nullability. Also, even though the types end up as nullable, VS does not generate any warnings about the lack of null checks.

Is this by design? If so, why?

Upvotes: 0

Views: 48

Answers (0)

Related Questions