?? not only a way to say I'm confused

Published 27 September 07 10:54 AM | Coding4Fun 

Scott Guthrie has a great post about question marks and LINQ.  Well, actually, it is about the c# null coalescing operator, ??.  So what does the ?? operator do?  It checks a value and if null, put in something different.

Old way:

string foo = arg[0];
if( foo == null)
    foo = "bar";

A new possible way using ??:

string foo = arg[0] ?? "bar";

What is even neater is you can chain values together to provide fallback.

string item = DBValue ?? ConfigValue ?? "SomeOtherValue";

Scott then goes on and demonstrates how to use this operator with LINQ.  He also promised to show how to do something similar with the LINQ to XML Literal support in VB.

Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# JLS said on September 27, 2007 3:27 PM:

This is not new.  It's been in C# since at least .NET 2.0, maybe longer.

# Michael said on October 1, 2007 5:50 PM:

What I'm missing is a complementary version to make it easier to write:

string foo = (bar == null) ? null : Foo(bar);

But it's hard to not laugh outright at the obvious choice for it:

string foo = bar !? Foo(bar)

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

Search

This Blog

Syndication

Page view tracker