Home > Mobile >  What is the point of making a reference type nullable?
What is the point of making a reference type nullable?

Time:11-27

The documentation for nullable reference types says:

The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type. The compiler doesn't add any runtime checking for non-nullable reference types. The benefits are in the compile-time analysis. The compiler generates warnings that help you find and fix potential null errors in your code. You declare your intent, and the compiler warns you when your code violates that intent.

What are the potential null errors? What intent do I declare using a nullable reference type? This is not clear to me.

CodePudding user response:

Originally, all reference-type variables were nullable. This meant that you always had to consider the possibility of a null reference and code accordingly. If it was your intention that a variable never be null, there was no way to enforce that. If you treated it like it would never be null, there was always the possibility of a NullReferenceException at run time if someone mistakenly set it to null.

Now, you can specify which variables should be nullable and which shouldn't and the compiler will enforce that. If you try to make a non-nullable variable null, a compiler error will prevent that. If you treat a nullable variable as though it definitely won't be null, a compiler warning will alert you.

CodePudding user response:

Maybe some sample code helps you to understand better:

string? myString1 = RemoveDots1("Hel.lo");
string myString2 = RemoveDots1("Hel.lo"); // warning: the function might return null, but you declared myString2 as non nullable.


myString1 = null;
myString2 = null; // warning: you should not do that, because you declared myString2 as non nullable.

myString1 = RemoveDots1(myString1);
myString1 = RemoveDots2(myString1); // warning: myString1 could be null, but its expecting a non nullable string


string? RemoveDots1(string? myString)
{
    return myString.Replace(".", ""); // warning: myString could be null
}


string RemoveDots2(string myString)
{
    return myString.Replace(".", "");
}
  • Related