22

How to use the Null-Coalescing Operator (??)

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This

A very handy operator that is always needed

Its always been common for all the developers while writing code to check for null condition when ever we use any object or value before we assign them. 

We always want to simplify checking for null values before we use a variable.

On a day to day basis we come across code bits like

                 

or like this

            DataTable data = GetDataFromDB();
            if (data != null)
            {
                dataGridView1.DataSource = data;
            }
            else
            {
                dataGridView1.DataSource = null;
            }

and so on…

So during these scenarios the null-coalescing operator can be very handy and can simplify the syntax a bit.

So with the use of this operator the above statements can be rewritten as follows

The second example can be rewritten as

            DataTable data = GetDataFromDB();
            dataGridView1.DataSource = data ?? null;

Isn’t this a handy operator ???

Please comment on this article..

prajapat