Home > other >  Why do I get possible null-assignment warning on nullable types
Why do I get possible null-assignment warning on nullable types

Time:08-28

class Test {
}

//Main method
Test ccc = null;
string sss = null;

I am wondering why do I get a warning when I assign null to a string or to a class? Both are perfectly nullable. If I add the nullable ? annotation and say

Test? ccc = null;
string? sss = null;

then the warning will go away. But internally nothing has changed. What is the point of this?

CodePudding user response:

What is the point of this?

The point is you can try to communicate, with the absence or presence of the ? mark, if the value of the reference type can be null, or not. And the C# compiler has static analysis that tries to assist you, so you do not run into a NullReferenceException as easily as you did in older versions of C#.

If you do not like it, it is possible to set nullable context to "disable". See link Nullable reference type for more.

CodePudding user response:

Null-state analysis tracks the null-state of references. This static analysis emits warnings when your code may dereference null. You can address these warnings to minimize incidences when the runtime throws a System.NullReferenceException. The compiler uses static analysis to determine the null-state of a variable. A variable is either not-null or maybe-null. The compiler determines that a variable is not-null in two ways:

The variable has been assigned a value that is known to be not null. The variable has been checked against null and hasn't been modified since that check. Any variable that the compiler hasn't determined as not-null is considered maybe-null. The analysis provides warnings in situations where you may accidentally dereference a null value. The compiler produces warnings based on the null-state.

When a variable is not-null, that variable may be dereferenced safely. When a variable is maybe-null, that variable must be checked to ensure that it isn't null before dereferencing it

https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references

  • Related