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

Madhu.b.rokkam
Posted by in C# category on for Intermediate level | Points: 250 | Views : 4331 red flag
Rating: 5 out of 5  
 1 vote(s)

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..

Conclusion

Hope everyone will like this and every developer will start using this operator and make their life easier.

As this is very simple one I am not attaching any code file for this.. Please try this.. Thanks

Page copy protected against web site content infringement by Copyscape

About the Author

Madhu.b.rokkam
Full Name: Madhu Rokkam
Member Level: Bronze
Member Status: Member,MVP
Member Since: 1/13/2011 3:13:20 PM
Country: India
Thanks and Regards Madhu
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Tripati_tutu on: 2/21/2011 | Points: 25
Nice article...
Posted by: Madhu.b.rokkam on: 2/21/2011 | Points: 25
Thanks for your comments
Posted by: Tripati.patro on: 2/21/2011 | Points: 25
Nice article Madhu.

Good use of examples..
Posted by: Madhu.b.rokkam on: 2/21/2011 | Points: 25
Thanks Tripati patro..
Posted by: Vijayakumarp on: 3/19/2012 | Points: 25
Nice article Madhu Rokkam....

Login to post response

Comment using Facebook(Author doesn't get notification)