Labels

Tuesday, April 29, 2008

C# ?? null coalescing operator - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extension Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword

?? null coalescing operator

This provides a nice, terse way to check whether a value is null, and if so return an alternate value.

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.

The ?? operator works for both reference types and value types.

String message = "Testing";

String result = message ?? "Null Value";

int? age = 55;

int retirement = age ?? 58;

Using the ?? operator with LINQ

Let's consider a scenario where we have an XML file or feed with the following contact data:

To handle such situation the use of ?? null operator comes in picture as below.

Reference: http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment