Home > OS >  In modern C#, can reference-typed variables be assigned the null value, or can't they?
In modern C#, can reference-typed variables be assigned the null value, or can't they?

Time:03-06

I've been trying to understand the implications of nullable reference types for a while now, but I'm still confused. My understanding is that, in a nullable context, you're not supposed to be able to do this:

TestClass nonNullable = null;
public class TestClass { }

I thought you're supposed to need to declare a reference type as nullable to be able to assign it a value of null in a nullable context, like this:

TestClass? nullable = null;

When I compile the first block of code in net5.0 or net6.0 with the Nullable node in the project file set to "enabled", all I get is a compiler warning CS8600. Other than that, everything seems to work the same. However, I understand that nullable reference types are a massive breaking change vis-a-vis older libraries. Why? I've read the Microsoft API reference on this topic: Nullable reference types, as well as chapters in two books. The behavior I'm observing seems to violate Microsoft's specification. Either I'm stupid, the explanations are inaccurate/unclear, or maybe both of these.

CodePudding user response:

Yes, reference variables in any nullable context can be assigned a null value.

"Nullable" and "non-nullable" reference variables are perhaps misleading terms here, because they only indicate whether the compiler should generate warnings for a given variable.

It's also a bit confusing that the context itself is called "nullable" and that enabling it makes reference variables non-nullable in that context, unless you specify otherwise.

TLDR: enable some version of the nullable context feature to generate related warnings at compile time - that's all it does.

As a side note, if you actually want to block your builds based on those warnings, you'll need to take additional steps. See this related answer: https://stackoverflow.com/a/62116924/3743418

  • Related