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

The Null-Coalescing Operator ??

, 16 Dec 2013
Rate this:
Please Sign up or sign in to vote.
About and how to use ?? operator

Introduction

This article is about to explain what is Null-Coalescing operator (??) and how to use it in your program. This is intended for beginners since basic knowledge about C#/Javascript is mandatory here.

"A nullable type can contain a value, or it can be undefined. 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 value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an exception will be thrown."

Background

So this is how I got an idea to write an article, When I was analysing the application for enhancement accidentally I came to see ?? operator. I astonished and too curious to know what is this operator means here(Initially I thought its typo error Wink | ;-) My bad).Then I started to dig about this operator and I want to share it here so that it may be useful for many people.

Using the code

A simple if condition will help you to understand the why we are going for ?? operator.

Initially I have declared

string firstName = null;
string lastName = "Prabakar";
string initials = "RK";
string output= string.Empty;

By using if condition to get not nullable value from FirstName,LastName and Initials I need to write like the below code

if (FirstName != null) {
  output = FirstName;
} else if(LastName != null) {
  output = LastName; 
} else {  
  output = Initials; 
} 

Now after checking the condition, lastName = "Prabakar" will be assigned to output variable.

This can be written as 

output = firstName ?? lastName ?? initials; 

Now in output variable you will get "Prabakar" which means it will return not nullable value to the variable. 

Now if the lastName is assigned as string.empty instead of "Prabakar" and lets see what you get in output variable

lastName = string.empty;   
output = firstName ?? lastName ?? initials; 

After executing this line in output variable you will have empty string ("") which is not null. Which denotes that ?? operator will return not nullable string from left to right order. 

Now lets change lastName to Null and lets see what happens to output variable

lastName = null;
output = firstName ?? lastName ?? initials; 

Now in output variable, you will get initials("RK") as return value.Since firstName and lastName are null,intials alone has string value so it is returned to output.

Why string is manipulated here, why cannot other data types, yeah lets try that too and see what happens

int x = null; 
int y= 10;
int z = 5;
int outputInt = x ?? y ?? z;

compiler would be not happy to process the above code, and throws the following error

Operator '??' cannot be applied to operands of type 'int' and 'int'

Which denotes it is not applicable to Not Null-able Int datatype.

 Here is how we can use ?? operator over Int  

int n = 10;  
int? x = null;  
int? z = x ?? n; 

Thanks to Nicholas Marty for his suggestion on Nullable-Int( Int? )  

Lets make compiler happy by altering the code instead of int we use object 

object x = null;
object y = 10;
object z = 5;
object output = x ?? y ?? z; 

Now we have made compiler happy Wink | ;-)

Okay we move further and ask the compiler whether it can handle methods in ?? operator

string result = myMethod() ?? "Default value"; 

Definitely we have made compiler happy.

In the above code we are trying to assign return value from myMethod(), if its null then without any delay "Default value" should be assigned to result variable.

Advantages of using ?? operator 

  • Code is well organized and readable.
  • If you are handling with session, configuration values it will be more helpful to assign alternate values to the variables. 

License

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

About the Author

♥…ЯҠ…♥
Software Developer
India India
There are only 10 type of people in this programming world....
one who knows the binary and other who doesn't.

Comments and Discussions

 
GeneralMy vote of 1 PinmemberPeter Nazarovs17-Dec-13 9:37 
GeneralRe: My vote of 1 Pinprofessional♥…ЯҠ…♥17-Dec-13 17:01 
QuestionGood article - I learned something new PinmemberGraham Wilson13-Dec-13 4:54 
AnswerRe: Good article - I learned something new Pinprofessional♥…ЯҠ…♥15-Dec-13 17:04 
QuestionA few ideas for this tip PinprofessionalNicholas Marty11-Dec-13 23:45 
AnswerRe: A few ideas for this tip Pinprofessional♥…ЯҠ…♥12-Dec-13 0:50 
GeneralMy vote of 5 PinprofessionalS. M. Ahasan Habib11-Dec-13 22:13 
GeneralRe: My vote of 5 Pinprofessional♥…ЯҠ…♥11-Dec-13 22:30 
QuestionNice Article PinmemberGarry Lowther11-Dec-13 21:41 
AnswerRe: Nice Article Pinprofessional♥…ЯҠ…♥11-Dec-13 22:30 
GeneralRe: Nice Article PinmemberGarry Lowther11-Dec-13 22:36 
GeneralRe: Nice Article Pinprofessional♥…ЯҠ…♥11-Dec-13 22:47 
GeneralRe: Nice Article PinmemberGarry Lowther11-Dec-13 22:50 
GeneralRe: Nice Article Pinprofessional♥…ЯҠ…♥11-Dec-13 23:06 
GeneralNot Bad PinmemberB I Khan11-Dec-13 21:34 
GeneralRe: Not Bad Pinprofessional♥…ЯҠ…♥11-Dec-13 21:47 

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 | Mobile
Web03 | 2.8.140718.1 | Last Updated 16 Dec 2013
Article Copyright 2013 by ♥…ЯҠ…♥
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid