Common C # idioms including coalesce? operator

Everyone knows at least two common C # idioms, including the coalesce operator:

singleton:

return _staticField = _staticField ?? new SingletonConstructor(); 

and chain:

 notNullableResult = nullable1 ?? nullable2 ?? nullable3 ?? default(someType); 

it is readable, consistent, deserving of use and recognizable in code.

But, unfortunately, thatโ€™s all. Sometimes he needs to expand or change. Sometimes I use them when I see a specific case, and I always hesitate to use it because I donโ€™t know if any other programmer will really read it easily.

Do you know others? I would like to have more specific uses: for example. Asp.net, EF, LINQ, everything where the union is not only acceptable, but also wonderful.

+7
c # null-coalescing-operator
source share
2 answers

For me, when it translates to SQL, itself is pretty good:

 from a in DB.Table select new { a.Id, Val = a.One ?? a.Two ??a.Three } 

As a result, in COALSCE on the database side, in most cases, a huge SQL cleaner is used, there is simply no great alternative. We use Oracle, I would prefer not to read, although Nvl(Nvl(Nvl(Nvl( thanks nested ... I will take my COALSCE and run it.

I also use it for properties such as personal taste, I think:

 private string _str; public string Str { get { return _str ?? (_str = LoaderThingyMethod()); } } 
+6
source share

The reason the null coalescing operator was introduced in C # 2.0 was because it was possible to assign default values โ€‹โ€‹to types with a null value, and thus it was easy to convert a type with a null value to a type that did not contain NULL. Without ?? any conversion will require a long if . The following quote is taken from MSDN :

A type with a null value may contain a value, or it may be undefined. The ?? The operator determines the default value for returns when a type with a null value is assigned to a type with a non-empty value. If you try to assign a value with a null value of type to a value type that is not null without using an operator, you will generate a compile-time error. If you use a throw, and a value with a null value type is currently undefined, an InvalidOperationException will be thrown.

You may consider the following simplification โ€œwonderfulโ€:

 int? x = null; int y = x ?? -1; 

Instead

 int? x = null; int y = -1; if (x.HasValue) { y = x.Value; } 
+4
source share

All Articles