Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

null

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?

like image 905
Eric Movsessian Avatar asked Aug 25 '26 17:08

Eric Movsessian


1 Answers

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.

like image 102
Jeppe Stig Nielsen Avatar answered Aug 28 '26 07:08

Jeppe Stig Nielsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!