The C# ?? null coalescing operator (and using it with LINQ)
page 2 of 5
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 24935/ 35

Simple Example Usages

Several folks have blogged about the ?? operator in the past - read here, here, here, and here for some previous examples on how to use it.  Simply put, the ?? operator checks whether the value provided on the left side of the expression is null, and if so it returns an alternate value indicated by the right side of the expression.  If the value provided on the left side of the expression isn't null, then it returns the original value. 

For example, let's assume we have a string variable "message".  We could check whether message was null, and return an alternate value using the code below:

Figure 1

Because the "message" variable above wasn't null, the "result" variable is assigned the original "hello world" message value. 

In the code snippet below, however, message is a null value, and so the ?? operator will return the alternate value we've provided:

Figure 2

The ?? operator works for both reference types and value types.  For example, below we are checking whether the nullable integer "number" variable is null.  Because it isn't, the result will be the original value (55):

Figure 3

If "number" is null, then result is assigned the value 0:

Figure 4


View Entire Article

User Comments

Title: C # Linq   
Name: Faheem
Date: 2009-05-21 7:43:20 AM
Comment:
hi
say i have 300 xml elements and 250 may or may not have their values in xml file then it will be very tedious for me to write all element name and using ? style as u mention . IS there any method which is universal and easy to use.
Title: ASP .Net   
Name: raja
Date: 2007-10-05 3:36:50 AM
Comment:
detail Above session






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-25 7:08:00 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search