views:

291

answers:

2

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.

+4  A: 

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()); } 
}
Nick Craver
A: 

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;
}
0xA3
yes, i should have specified that a chain is usually about nullables. thank you.
rudnev
The null coalescing operator was actually introduced in C# 2.0, not 3.0 (same as nullable types)
Thomas Levesque
@Thomas Levesque: You are right, I stand corrected.
0xA3