C# 6.0 Feature :Null Conditional Operator


Null Conditional Operator

If you are an experience programmer then you often got this 'NullReferenceException' exception.

It is because you forgot to check the condition for null.

For that you have to write code for checking null condition. But In C# 6.0, same code can be implemented using null conditional operator '?.'.

See the below example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewInCSharp6
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer();
                       
            cust.Name = "Peter hensan";
            cust.Address = "";

            //Before
            Console.WriteLine("Before");
            if (cust.Address != null)
            {
                Console.WriteLine("Name : {0} Address : {1}", cust.Name, cust.Address);
            }
            else
            {
                Console.WriteLine("Name : {0}  Address : {1}", cust.Name, string.Empty);
            }
            
            // In C#6 
            Console.WriteLine("In C#6");
            Console.WriteLine("Name : {0}  Address : {1}", cust.Name, cust?.Address);

            Console.ReadLine();
        }
    }   

    public class Customer
    {        
        public string Name { get; set; }
        public string Address { get; set; }
    }
    
}























C# 6.0 Feature :Null Conditional Operator C# 6.0 Feature :Null Conditional Operator Reviewed by kamal kumar das on December 05, 2016 Rating: 5

No comments:

ads 728x90 B
Powered by Blogger.