LINQed IN

Blog by Troy Magennis on Software Architecture, Development and Management

About the author

Troy Magennis is a software developer living in Seattle, WA. Troy is a Microsoft MVP, the author of many articles, and the founder of HookedOnLINQ.com, a LINQ specific wiki reference site.
E-mail me Send mail

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Null Coalescing Operator

This came up today in the office, so I thought i'd post a reminder of a useful operator in C# that first appeared in C# 2.0.

When Nullable Types were introduced, Microsoft also added an operator to make dealing with null values easier. This avoids a lot of if/else checking for null values.

The normal form is:  [variable] ?? [value if variable is null]

A simple example is when dealing with nullable types, like nullable int values -

int? i = null;
int? j = 42;

int result1 = i ?? 0; // result1 is 0
int result2 = j ?? 0; // result2 is 42

The results are: result1 = 0 (because i was null), and result2 = 42 (because j had a value).

The null coalescing operator removes a lot of the clutter of testing a variable for null and assigning a default value. This is often necessary when casting a nullable type back to its non-nullable counterpart.

To read more see lots of references on this Google  search.

Troy.


Tags:
Categories: C#
Posted by t_magennis on Tuesday, November 20, 2007 5:05 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading