When I write this statement:
var x = new ClassName();
x is implicitly typed as a ClassName?. That is, since ClassName is a reference type, implicit assignments using var automatically define as nullable (even when I am providing a non-null instance and never modifying it).
My question is, is there any way to make non-nullability the default when using the "var" keyword?
I'm aware of this question and associated info: Why does Visual Studio Type a Newly Minted Array as Nullable?
No, as it is stated in the docs -
varalways implies nullable reference type: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):
Demo
If for some reason you still need explicitly non-nullable type you can work around with target typed new expressions in some cases:
Also you can consider disabling nullable reference types (locally of for the whole project) or using null-forgiving operator (
!).