I'm learning C# and trying to handle the influx of "a
could be null
" warnings.
I was wondering, since it's such a common case to error out when something is null, either by returning from the function or throwing an exception, does C# have some kind of syntactical sugar for that case ?
Example of what I have in mind: int a = obtainA() ??? { Console.WriteLine("Fatal error;") return };
(this is not real code)
I know about the ??
and ??=
operators, but they don't seem to help much here and I haven't found better.
If not, what would be the closest we have to emulating this ? Is there no better way than to write the following ?
int? nullableA = obtainA();
int a;
if (nullableA.HasValue) {
a = nullableA.Value;
}
else {
Console.WriteLine("Fatal error");
return;
}
/* use a, or skip defining a and trust the static analyzer to notice nullableA is not null */