Mladen Prajdić Blog

Blog about stuff and things and stuff. Mostly about SQL server and .Net

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. :))

Legacy Comments


Rob Cannon
2006-03-27
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).

mladen
2006-03-28
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 :))

Bino
2008-09-05
re: C# 2.0 ?? Operator
Coalesce operator can only be used for NULL values?




www.codepal.co.in

good
2008-10-13
re: C# 2.0 ?? Operator
coooooooooooooooooooolllllllllllll