Search code examples
c#c#-8.0nullable-reference-types

What is the point of making a reference type nullable?


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.


Solution

  • 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(".", "");
    }