Click here to Skip to main content
Click here to Skip to main content

?? Operator

, 12 Mar 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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

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

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:

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

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.

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

while with the ternary operator you are left with either:

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. 

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)

Share

About the Author

Muthu Nadar
Team Leader
India India
No Biography provided
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralDisadvantage? PinmemberAndrew Rissing12-Mar-12 4:58 
GeneralRe: Disadvantage? PinmemberMuthukumar Nadar14-Mar-12 19:48 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 12 Mar 2012
Article Copyright 2012 by Muthu Nadar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid