Monday, March 29, 2010
Most everyone is familiar with the C# construct of the conditional operator:

        (binary expr) ? true_result : false_result

However I've found that many people often overlook the null-coalescing operator ??. I see a lot of code that examines a string and assigns a value to it if it's null (like a default perhaps):

        string s;
...
        s = (title == null) ? "default" : title;

However, this can be written more simply using the ?? operator:

        s = title ?? "default";

This construct comes in handy when using nullable types and particularly converting them back into non-nullable types:

        int? i = null;
        int counter = i ?? 0;

Enjoy Programming in C#! (and don't forget: You got a test for that??)

C#
Monday, March 29, 2010 7:45:31 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]  |  Trackback
© Copyright 2012, John E. Boal