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

?? Operator

By , 12 Mar 2012
 

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)

About the Author

Muthukumar Nadar
Software Developer Team computers
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralDisadvantage?memberAndrew Rissing12 Mar '12 - 3:58 
GeneralRe: Disadvantage?memberMuthukumar Nadar14 Mar '12 - 18:48 
Yes Sir, that is my mistake
Actually I gave that point their just to bring an awareness on, it doesn't handle empty string.
If I kept it under NOTE: it would be correct.

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

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