Can a non-nullable reference type in C# 8 be null in runtime?

This is what MS says about (https://docs.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.


You are correct, other code which is not using the new feature could assign null to this property, there are no run-time checks it is just complier hints.

You could always do it yourself if you want a runtime check:

public string Test { get; set{ if (value == null) throw new ArgumentNullException() } }

Note that you can guarantee not being null in most of your code, you just need to add guards to your top-level Public API and make sure classes are appropriately sealed etc.

Of course people can still use reflection to f*** your code up, but then its on them


someone can always do

var myFoo = new Foo(null);

May be you can use Domain Driven Design

public class Foo
{
    public Foo(string test)
    {
         if (string.IsNullOrWhiteSpace(test))
             throw new ArgumentNullException(nameof(test));

         Test = test;
    }
    public string Test {get;private set;}
}