Consider the following code, written in a nullable-references-enabled context:
static string GetStr() => "test";
public static void Main() {
var s = GetStr();
}
s
is implicitly typed as a string?
rather than a string
.
This is by design, as it's mentioned on MSDN's official documentation for var:
When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable.
But why is this? Is it because the variable may be re-assigned later?
Furthermore, even though it's typed as string?
I can dereference it without a warning:
if (s.Length > 10) return; // Emits no compiler warning
However, if I create another method that does return a string?
the compiler now emits a warning if I attempt a dereference, even though both variables are typed as string?
:
static string? GetStrMaybe() => "test";
public static void Main() {
var s = GetStrMaybe();
if (s.Length > 10) return; // Compiler emits a warning because I'm dereferencing 's' without checking for null
}
Is the answer basically "the compiler is tracking null state in the background", and that the implicitly-typed variable types are kind of to-be-ignored?
I find this weird because in both cases, s
is typed as string?
, but only in the latter example does the compiler emit a warning if I dereference without a check. Which, to be clear, is what I'd expect in the end, but it's just the way we get there that's confusing me.