Page 1 of 1

Null Coalescing (? ?) and Inline-If (?:) -- Somewhat lesser known oper

#1 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon

Reputation: 4311
  • View blog
  • Posts: 7,467
  • Joined: 08-June 10

Posted 14 June 2010 - 07:21 PM


Note to moderator: the ?? in the title will not display as is. It seems to strip the second ? when I put them together. I've included a space so it is not removed, but I'd like to know if it's possible to make it correct.

?? is a C# binary operator used to provide a default value should the left operand be null. For example:

X = A ?? B;

equates to:
if(A != null)
  X = A;
  X = B;

Relatively simple, but a great time saver, and sometimes quite useful. Another example:
string result = ( TextBox1 ?? new TextBox() ).Text;

In this example, if TextBox1 is not null, result will contain TextBox1.Text. Otherwise, it will contain a blank string, since that is what new TextBoxes are initialized to.

Another example, one that I actually use all the time:
System.Windows.Controls.CheckBox.IsChecked is a nullable bool, meaning its value can be either true, false, or null. I want to equate null to false. Here's how I'd do it:

//myCheckBox is a checkbox defined in the XAML file
if(myCheckBox.IsChecked ?? false)

If the checkbox's state is null, it is replaced with the value false.


?: is a C# (and many other languages) ternary operator used to return a value based on the evaluation of a boolean expression. This one is far more commonly known than the ?? operator, because it has its roots in C, but I'm still surprised at how many people don't know how to use it. Here's an example of how it works:

X = A ? B : C;

This is equivalent to:
  X = B;
  X = C;

A more practical example:
string substr = fullstr.Length > 10 ? fullstr.Substring(0, 10) : fullstr;

This code sets substr's value to the first 10 characters of fullstr, unless fullstr is shorter than 10 characters, in which case, substr is assigned the value of fullstr.

Hope you found this enlightening!

Is This A Good Question/Topic? 7
  • +

Replies To: Null Coalescing (? ?) and Inline-If (?:) -- Somewhat lesser known oper

#2 LetMeFinclOut  Icon User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 115
  • Joined: 14-May 09

Posted 24 June 2010 - 12:31 AM

I've only recently learned of the ?? operator while preparing to take a certification exam. Really wish I new of it earlier, as it seems incredibly useful.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1