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?
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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With