Using the Null Coalescing Operator

The null coalescing operator is a cool tool that can be used to assign a custom default value to a null variable using two question marks (“??”). It’s perfect for situations in which you want to use the value of a particular variable, but want to be able to use a default value just in case that variable has no value. Here’s how to use it:

static string _colors;
static string Colors
    {
	get
	{
	    return _colors ?? "White";
	}
	set
	{
	    _colors = value;
	}
    }

    static void Main()
    {
	Console.WriteLine(Colors);
	Colors = "Purple";
	Console.WriteLine(Colors);
	Colors = null;
	Console.WriteLine(Colors);
    }

The output of the above code should be as follows:

White
Purple
White

By using the null coalescing operator (“??”) to set the default value of the _colors variable to “White”, that’s what’s going to appear on the console when colors hasn’t been assigned any value, like in the first line of Main(): Console.WriteLine(Colors), and like in the last line: Console.WriteLine(Colors) where Colors = null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download