Everyone knows at least two common c# idioms including coalesce operator:
a singleton one:
return _staticField = _staticField ?? new SingletonConstructor();
and a chain one:
notNullableResult = nullable1 ?? nullable2 ?? nullable3 ?? default(someType);
it's readable, consistent, worth using and recognizable in code.
But, unfortunately, this is all. Sometimes it will need expanding or change. Sometimes i use them when i see a particular case - and always i hesitate to use it because i dont know if any other programmer will really read it easy.
Do you know any others? I would love to have more specific usages: e.g. Asp.net, EF, LINQ, anything - where coalesce is not only acceptable but remarkable.
For me, where it translates to SQL is good enough by itself:
from a in DB.Table
select new {
a.Id,
Val = a.One ?? a.Two ??a.Three
}
This resulting in COALSCE
on the database side makes for tremendously cleaner SQL in most cases, there just isn't any great alternative. We're using Oracle, I'd rather not read though Nvl(Nvl(Nvl(Nvl(
nesting thank you...I'll take my COALSCE
and run with it.
I also use it for properties like this, just personal taste I guess:
private string _str;
public string Str {
get { return _str ?? (_str = LoaderThingyMethod()); }
}
The reason that the null-coalescing operator has been introduced in C# 2.0 was to have an way to assign default values to nullable types and thus easily convert a nullable type into a non-nullable type. Without ??
any conversion would require a lengthy if
statement. The following quote is taken from MSDN:
A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.
You might consider the following simplification "remarkable":
int? x = null;
int y = x ?? -1;
Instead of
int? x = null;
int y = -1;
if (x.HasValue)
{
y = x.Value;
}
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