Thursday, May 4

C# COALESCE operator

A useful function in T-SQL is COALESCE, which takes two arguments and returns the first if it is not null and the second if the first is null.

I found out today about a feature in C# 2.0 that I had somehow missed which does the same thing (via Avner Kashtan's blog).

String a = null;
String b = "abc";
String c = a ?? b;

returns "abc".

These can also be chained, so the first non-null argument is returned, so

String a = null;
String b = null;
String c = "abc";
String d = a ?? b ?? c;

returns "abc".

It's a lot easier to read than the alternative:

String d = (a != null ? a : (b != null ? b : c))

No comments: