Click here to Skip to main content
15,885,065 members
Articles / Programming Languages / C#
Tip/Trick

The Null-Coalescing Operator ??

Rate me:
Please Sign up or sign in to vote.
4.64/5 (10 votes)
16 Dec 2013CPOL3 min read 28K   11   16
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 ;-) 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

C#
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

C#
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 

C#
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 = 10int? 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 ;-)

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

C#
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)


Written By
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 Pin
Peter Nazarovs17-Dec-13 9:37
professionalPeter Nazarovs17-Dec-13 9:37 
GeneralRe: My vote of 1 Pin
♥…ЯҠ…♥17-Dec-13 17:01
professional♥…ЯҠ…♥17-Dec-13 17:01 
QuestionGood article - I learned something new Pin
Graham Wilson13-Dec-13 4:54
Graham Wilson13-Dec-13 4:54 
AnswerRe: Good article - I learned something new Pin
♥…ЯҠ…♥15-Dec-13 17:04
professional♥…ЯҠ…♥15-Dec-13 17:04 
QuestionA few ideas for this tip Pin
Nicholas Marty11-Dec-13 23:45
professionalNicholas Marty11-Dec-13 23:45 
AnswerRe: A few ideas for this tip Pin
♥…ЯҠ…♥12-Dec-13 0:50
professional♥…ЯҠ…♥12-Dec-13 0:50 
GeneralMy vote of 5 Pin
S. M. Ahasan Habib11-Dec-13 22:13
professionalS. M. Ahasan Habib11-Dec-13 22:13 
GeneralRe: My vote of 5 Pin
♥…ЯҠ…♥11-Dec-13 22:30
professional♥…ЯҠ…♥11-Dec-13 22:30 
QuestionNice Article Pin
Garry Lowther11-Dec-13 21:41
Garry Lowther11-Dec-13 21:41 
AnswerRe: Nice Article Pin
♥…ЯҠ…♥11-Dec-13 22:30
professional♥…ЯҠ…♥11-Dec-13 22:30 
GeneralRe: Nice Article Pin
Garry Lowther11-Dec-13 22:36
Garry Lowther11-Dec-13 22:36 
GeneralRe: Nice Article Pin
♥…ЯҠ…♥11-Dec-13 22:47
professional♥…ЯҠ…♥11-Dec-13 22:47 
GeneralRe: Nice Article Pin
Garry Lowther11-Dec-13 22:50
Garry Lowther11-Dec-13 22:50 
Yes - in this case - it is like a ternary operator which I first encountered learning C in the 1980's.
I am only advising caution to the ECMA group for C# to please stop growing the language and focus instead on getting it onto every hardware device and operating system.
Garry Lowther
CEO and Founder
TriSys Business Software
Cambridge, England
www.trisys.co.uk

GeneralRe: Nice Article Pin
♥…ЯҠ…♥11-Dec-13 23:06
professional♥…ЯҠ…♥11-Dec-13 23:06 
GeneralNot Bad Pin
B I Khan11-Dec-13 21:34
B I Khan11-Dec-13 21:34 
GeneralRe: Not Bad Pin
♥…ЯҠ…♥11-Dec-13 21:47
professional♥…ЯҠ…♥11-Dec-13 21:47 

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.