Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 293
Ilya Chernomordik Avatar asked Dec 30 '19 12:12

Ilya Chernomordik


2 Answers

Even in your own code, if you choose to do so, you can pass null, using the null-forgiving operator. null! is considered to be not-null so far as the compiler's nullability analysis is concerned.

like image 64
Damien_The_Unbeliever Avatar answered Oct 10 '22 05:10

Damien_The_Unbeliever


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.

like image 41
Dmitri Tsoy Avatar answered Oct 10 '22 04:10

Dmitri Tsoy