I want some Moore

Blog about stuff and things and stuff. Mostly about SQL server and .Net
posts - 226, comments - 2295, trackbacks - 33

My Links



Hi! My name is 
Mladen Prajdić  I'm from Slovenia and I'm currently working as a .Net (C#) and SQL Server developer.

I also speak at local user group meetings and conferences like SQLBits and NT Conference
Welcome to my blog.
SQL Server MVP

My Books

SQL Server MVP Deep Dives 2
The Red Gate Guide to SQL Server Team based Development Free e-book

My Blog Feed via Email
Follow MladenPrajdic on Twitter

Users Online: who's online

Article Categories


Post Categories

Cool software

Other Blogs

Other stuff

SQL stuff

C# 2.0 ?? Operator

I saw this operator in use today in a code example. I must say when I figured what it does my geek side went "YES!!!!".
It resembles an old "if" abbreviation:

(condition ? true result : false result);
now what ?? does is a null check same as the SQL Servers Coalesce function. It returns the first non null parameter.
function test(class1 variable)
    if (variable == null)
        variable = new class1();
    // equals to
    variable = (variable ?? new class1());

I'm starting to use this and giving a "What!?!???" moment when they see it and a "Yes!!" moment when they figure it out to anyone who's going to look at my code from now on. :))

Print | posted on Monday, March 27, 2006 12:35 PM | Filed Under [ .Net ]



# re: C# 2.0 ?? Operator

I don't think that your two expressions are not the same.

if (variable == null)
variable = new class1();

At the end of this statement, variable is not null.

(variable ?? new class1());

This does not do an assignment and if variable is null before the statment is executed, it will still be null. This can be dangerous if this cause a new class1 to be created every time the expression is evaluated.

variable = variable ?? new class1();

This is closer to what you want, but the assignment is made every time (unless the optimizer takes care of that).
3/27/2006 3:40 PM | Rob Cannon

# re: C# 2.0 ?? Operator

well it returns the first non null parameter so i guess it's how you program it :))

oh and thanx for the check.... copy paste sometimes sucks :))
3/28/2006 3:59 PM | mladen

# Interesting use of C#'s ?? Coalesce operator when interating through a collection

Interesting use of C#'s ?? Coalesce operator when interating through a collection
10/9/2006 12:36 PM | I want some Moore!

# Interesting use of C# 2.0 ?? Coalesce operator when iterating through a collection

Ever since I discovered the ?? colaesce operator I embraced it with full force. Today I discovered another
11/21/2006 1:03 PM | SQL Server Feed Roller

# re: C# 2.0 ?? Operator

Coalesce operator can only be used for NULL values?

9/5/2008 10:53 AM | Bino

# re: C# 2.0 ?? Operator

10/13/2008 6:20 AM | good
Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET