Nullable and null coalescing operator

Null coalescing operator
in C# there exists an operator ‘??’ which is null coalescing operator. This operator has two operands. If first is null then it takes second and if not then it takes first.
Eg. If we want to assign our ‘previousForm’ variable to new variable ‘form’ if it is not null and if it is create new and assign then we can write as

Form form = null;
if(previousForm ! = null)
form = previousForm;
form = new Form();

also we can write

Form form = previousForm == null ? new Form() : prevousForm;

Now using null coalescing operator, we can write as

Form form = previousForm ?? new Form();

is more effecient.

Nullable type
If we want to pass null parameter in bool field through function, it cannot be done easily because bool can either false or true but not null.

This issue can be resolved by using ‘?’ operator as in following example

using System;
using System.Collections.Generic;
using System.Text;

namespace ConApp.NullCoal
class Program
static void Main(string[] args)
NullableBoolCheck(null); //We can pass null as bool parameter


static void NullableBoolCheck(bool? param)



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s