is there any way to make non-nullability the default when using the "var" keyword
No, as it is stated in the docs - var
always implies nullable reference type:
When var
is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable. The compiler's null state analysis protects against dereferencing a potential null value. If the variable is never assigned to an expression that maybe null, the compiler won't emit any warnings. If you assign the variable to an expression that might be null, you must test that it isn't null before dereferencing it to avoid any warnings.
But null state analysis can determine if variable is not actually null and do not emit warnings in quite a lot of cases (hence the part with emphasis in the quote):
public class C
{
public string M(string? j) {
var foo = "";
var bar = j;
// return foo; // no warning
return bar; // warning
}
}
Demo
If for some reason you still need explicitly non-nullable type you can work around with target typed new expressions in some cases:
MyClass x = new();
Also you can consider disabling nullable reference types (locally of for the whole project) or using null-forgiving operator (!
).
var
type inference, but that how the language was designed, which was t make usingvar
with nullable reference types easier. – Guernseynew
handles target typing, so you could doClassName x = new();
– Guernsey<Nullable>enable</Nullable>
to<Nullable>disable</Nullable>
. You can also change nullability in your code by placing#nullable disable ... #nullable enable
around your properties. – Chapelconst x =
or F#'slet x =
- a semantic way to declare that this identifier is permanently bound to the initially set value (and thus, if the initial value is not null, the identifier never will be either). (I realize thatvar
is still going to allow the value to vary, but I want to at least establish that it should never be set to null.) – Collotype