C# 8.0 – Can Non-Nullable Reference Type Be Null at Runtime?

c#-8.0c++nullable-reference-types

It seems to me there is really no guarantee that a non-nullable variable won't ever have null. Imagine I have a class that has one property that is not nullable:

public class Foo
{
    public Foo(string test)
    {
        Test = test;
    }
    public string Test {get;set;}
}

Now that might seem like it's now cannot be null. But if we reference this class with another library that does not use nullable context, nothing stops it from sending null in there.

Is that correct or there are some runtime checks as well perhaps that ensure this?

Best Answer

This is what MS says about (https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/upgrade-to-nullable-references#interfaces-with-external-code):

The compiler can't validate all calls to your public APIs, even if your code is compiled with nullable annotation contexts enabled. Furthermore, your libraries may be consumed by projects that have not yet opted into using nullable reference types. Validate inputs to public APIs even though you've declared them as nonnullable types.