Learn‎ > ‎.NET‎ > ‎C#‎ > ‎Tutorials‎ > ‎

Code Better

posted Nov 24, 2010, 10:52 AM by Shaukat Mahmood Ahmad   [ updated Nov 24, 2010, 11:00 AM ]

Null Coalescing Operator (??)

This one is such an elegant little operator that can be extremely useful in some situations.  How often do you have a variable that you want to use the value of, but if that value is null you want to substitute a default value?  For example, say you wanted to assign a string to a variable, but if that string is null you want the empty string instead?

You could, of course, write an if statement:

   1: string name = value;
   3: if (value == null)
   4: {
   5:     name = string.Empty;
   6: }