Later Today: ASP.NET Tutorial 2: Introduction to C#

(C#) Null Coalescing Operator (setting default variable values)

Prerequisites: Basic knowledge of variables and assigning values.

The purpose of the Null Coalescing Operator ( ?? ) is to set a default value for a variable in the event the first value you are attempting to assign from is null. Hence, the logic behind the null coalescing operator is this: If this variable is null, use this other value instead.

This is handy is because what would otherwise be a multiple-line if/else block is now a single, concise line.

v Scenario

Let’s say you want the value of a string called strCurrentName to be set the same as the value of another string called strPreviousName, but you know that there’s a chance that strPreviousName could be null and if it is you simply want to give strPreviousName a valued of “No Name Entered”.

What you would do is this

C#:
/*
Here we'd prefer to use strCustomerName, but there's a chance it may be null SO...
if strCustomerName is null, then strCurrentName gets "Name Unknown" instead.
*/
string strCurrentName = strCustomerName ?? "Name Unknown";

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...