C#’s null coalescing operator

I’ve been programming in C# for about five years, and today whilst reading the C# language specification v3.0, came across the null coalescing operator.

Much like T-SQL’s ISNULL function, the operator replaces null values with the specified replacement value.

So, in T-SQL

	SELECT
		ISNULL( Fieldname, '')
	FROM
		TableName

In C#, the ?? operator is the ISNULL equivalent. So, we have the following in C#

	string nullString = null;

	string anotherString = nullString ?? "It was null";

	// anotherString now contains "It was null"

	string myName = "Shane";

	anotherString = myName ?? "Name is null";

	// anotherString now contains "Shane"

Hardly revolutionary stuff, but I’ve never seen the operator before, so either it’s been discussed and regarded as useless, or other people are unaware of it, like I was until about 10 minutes ago.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.