In C# 8.0, suppose I have nullable references enabled with <Nullable>enable</Nullable>
in the .csproj. This gives me warnings when I try to use possibly-null references in a non-nonnullable usage, so that's great. I can then turn on <WarningsAsErrors />
and get this strictly enforced as errors rather than warnings.
So I was hopeful with this language construct that I could avoid certain null-checking code. Specifically, I (and many others) often wrote methods like this:
public string Message { get; set; }
public void SetFoo(string message) {
Message = message ?? throw new ArgumentNullException(nameof(message));
Console.WriteLine(Message.ToUpper())
}
I was hopeful to drop the null check, since the reference is non-nullable, and instead write
public string Message { get; set; }
public void SetFoo(string message) {
Message = message;
Console.WriteLine(Message.ToUpper())
}
This seems to be good, in that a call like myThing.SetFoo(null);
generates a compiler warning/error. However, I find that code such as myThing.SetFoo(null!);
compiles and runs anyway! So, in order to code defensively, I need to keep the old guard clause anyway in case someone calls it with such misuse of the !
operator, right?
Is there any way to avoid writing code to check for null on non-nullable references? I'd expect that there could be a way to make the compiler infer that it should throw an exception in such cases rather than just ignoring non-nullability, but I don't see it.
To remove these warnings, you need to add code to change that variable's null-state to not-null before dereferencing it. The collection initializer warning may be harder to spot. The compiler detects that the collection maybe-null when the initializer adds elements to it.
In simple language we can say that the code that validates your method's input is called a Guard clause. It makes your code more understandable and it protects you from bugs and unexpected behaviors. The if block act as a guard clause by protecting the GetStudent method against any null _student arguments.
Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.
Can we avoid null reference guard clauses with non-nullable method parameters in C# 8.0?
No, because:
null
s explicitly, using null!
, which has its usages, see also this question.null
, without getting warnings or errors in the calling project.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