Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it still possible to assign null to non nullable reference type?

I am confused. I thought enabling c# 8 and nullable reference types will prevent the assignment of null to a non nullable reference types, but apparently it is only a warning at compile time, I know you can enforce it to be an error and stop it build, but I thought it is more than just a compiler check.

Look at this example https://dotnetfiddle.net/4eCs5L

If you run, it is still possible to assign null to non nullable reference type, why isn't that throwing an error at run time?

like image 797
Mocas Avatar asked May 06 '20 04:05

Mocas


People also ask

What is the purpose of nullable reference types?

With the addition of nullable reference types, you can declare your intent more clearly. The null value is the correct way to represent that a variable doesn't refer to a value. Don't use this feature to remove all null values from your code. Rather, you should declare your intent to the compiler and other developers that read your code.

What is the difference between notnull and nullable in Java?

The variables notNull and nullable are both represented by the String type. Because the non-nullable and nullable types are both stored as the same type, there are several locations where using a nullable reference type isn't allowed. In general, a nullable reference type can't be used as a base class or implemented interface.

What are the values for the Nullable annotation Context?

There are four values for the nullable annotation context: Nullable warnings are disabled. All reference type variables are nullable reference types. You can't declare a variable as a nullable reference type using the ? suffix on the type. You can use the null forgiving operator, !, but it has no effect.

Can a non-nullable reference be initialized to null?

Arrays and structs that contain reference types are known pitfalls in nullable references and the static analysis that determines null safety. In both situations, a non-nullable reference may be initialized to null, without generating warnings. A struct that contains non-nullable reference types allows assigning default for it without any warnings.


1 Answers

TLDR: Backwards compatibility

If Nullable Reference Types would have been part of C# 1, then a null assignment to a non-nullable type would emit a compile error.

The problem of C# is there is already a lot of existing code without Nullable Reference Types. Compiler errors on null assignment would break all that existing code or libraries.

You can find the full explanation in the .NET Blog Post from the C# Program Manager: https://devblogs.microsoft.com/dotnet/nullable-reference-types-in-csharp/

like image 94
Christian Held Avatar answered Sep 18 '22 15:09

Christian Held