Tuesday, 23 October 2007

C# Coalesce

The ?? coalesce operator checks whether the value on the left hand side of the expression is null, if so it returns the value on the right hand side. If the value on the left hand side is not null, then the left hand side value is returned:

string message = "Hi Devs";
string result = message ?? "It was null!";

// Outcome: result == "Hi Devs"


string message = null;
string result = message ?? "It was null!";

// Outcome: result == "Message was null"


Note that this is a short-circuited operator. For example:

a = b ?? c;
translates to:
a = ( b == null ? c : b);
Which means the expression c is only evaluated if b is null. There is no equivalent in VB (short of performing an iif())

2 comments:

Seth said...

Have you tried using Coalesce to assign a querystring attribute to a string object when you are not sure if the attribute will exist?

for ict 99 said...

C-Sharp Training | C# Online Training | C Sharp Training | C# Training Online