Click here to Skip to main content
15,860,844 members
Articles / Web Development / ASP.NET
Tip/Trick

?? Operator

Rate me:
Please Sign up or sign in to vote.
4.20/5 (4 votes)
12 Mar 2012CPOL2 min read 14.8K   2   2
This article will explain about null coalescing operator along with its advantage and disadvantage.

Introduction

This article will explain about null coalescing operator along with its advantage and disadvantage.

Using the code

Starting with how to assign null value type to non-nullable type.
Nullable types are declared in one of two ways: 

Blocks of code should be set as style "Formatted" like this:

C#
System.Nullable<T> variable
-or-
T? variable  

Where T can be any value type including struct; it cannot be a reference type.

Examples of Nullable Types

C#
int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];

Now coming to the main point, ?? operator

One of the best features of C# is the ?? "null coalescing" operator.  This provides a nice way to check whether a value is null, and if so return an alternate value.

The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable type to a non-nullable type without using the ?? operator, you will generate a compile-time error.

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

Example

C#
class NullCoalesce
{
    static int? GetNullableInt()
    {
        return null;
    }

    static string GetStringValue()
    {
        return null;
    }

    static void Main()
    {
        // ?? operator example.
        int? x = null;

        // y = x, unless x is null, in which case y = -1.
        int y = x ?? -1;

        // Assign i to return value of method, unless
        // return value is null, in which case assign
        // default value of int to i.
        int i = GetNullableInt() ?? default(int);

        string s = GetStringValue();
        // ?? also works with reference types. 
        // Display contents of s, unless s is null, 
        // in which case display "Unspecified".
        Console.WriteLine(s ?? "Unspecified");
    }
} 

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

We can achieve the same by using ternary operator (that most are familiar with), then why to use null coalescing operator

Advantage

Well, first of all, it's much easier to chain than the standard ternary:

C#
string anybody = parm1 ?? localDefault ?? globalDefault;

vs

string anyboby = (parm1 != null) ? parm1 : ((localDefault != null) ? localDefault : globalDefault);


It also works well if null-possible object isn't a variable:

string anybody = Parameters["Name"] ?? Settings["Name"] ?? GlobalSetting["Name"];

vs

C#
string anybody = (Parameters["Name"] != null ? Parameters["Name"] : (Settings["Name"] != null) ? Settings["Name"] :  GlobalSetting["Name"];

The chaining is a big plus for the operator, removes a bunch of redundant IFs


Secondly, The ternary operator requires a double evaluation or a temporary variable.

C#
string result = MyMethod() ?? "default value";

while with the ternary operator you are left with either:

C#
string result = (MyMethod () != null ? MyMethod () : "default value");

which calls MyMethod twice, or:

string methodResult = MyMethod (); 
string result = (methodResult != null ? methodResult : "default value");

Either way, the null coalescing operator is cleaner and, I guess, more efficient.

Third it is readable

Disadvantage 

Only problem is the null-coalesce operator doesn't detect empty strings. 

C#
string result1 = string.empty ?? "dead code!";
string result2 = null ?? "coalesced!";

OUTPUT:

result1 = ""
result2 = coalesced! 

Well it is the null -coalescing operator, not the nullOrEmpty -coalescing operator.
You can achieve the same with Extension methods 

Thank you...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralDisadvantage? PinPopular
Andrew Rissing12-Mar-12 3:58
Andrew Rissing12-Mar-12 3:58 
GeneralRe: Disadvantage? Pin
Muthu Nadar14-Mar-12 18:48
Muthu Nadar14-Mar-12 18:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.