A Responsive Blogger Website, That Take my blog to the next level.

I am a Software Developer, Learning and experementing with .Net Technology and try to put my Learning altogether here.


We have all sections related to .Net Technology, like .Net-C#, Asp.Net, MVC, jQuery, AngularJs, Sharepoint. Find out more...


Following are the some of the Advantages of using this Web site :-

  • Get Update about latest in .Net world.
  • Collection of Useful, Frequently used .Net Solutions.
  • It’s beautiful on every screen size (try resizing your browser!)
by

3. New Features in C# 6.0 - Null Conditional Operators



Who hasn’t heard of NullReferenceException? I am sure all of us. To avoid this, we use enormous If conditions for null checking.

Let us consider the code listing below. We have a list of “Author”. Before fetching the Name of a particular Author, we are performing the null checking in if statement. If we do not do that, a NullReferenceException will be thrown.

static void Main(string[] args)
        {
            Author author = null;
            List<Author> lstAuthors = new List<Author>();
            lstAuthors.Add(author);
            foreach(var a in lstAuthors)
            {
                if (a != null)
                {
                    var name = a.Name;
                    WriteLine(name);
                }
            }

            ReadKey(true);
        }

 In C# 6.0, we can avoid if statements by using Null Conditional Operators.  We can rewrite the above code for the null checking as shown in the listing below:

static void Main(string[] args)
        {
            Author author = null;
            List<Author> lstAuthors = new List<Author>();
            lstAuthors.Add(author);
            foreach(var a in lstAuthors)
            {
                var name = a?.Name;
                Write(name);
            }

            ReadKey(true);
        }

 In C#6.0 it is very easy to do the null reference checking using the null conditional operator (?). I am sure this feature would be wildly used, hence it’s one of my favorite features of C# 6.0.

0 comments :