As we know C# 6.0 introduced with Visual Studio 2015. There are several features introduced in several version of the C# like LINQ was introduced with C# 3.0, Dynamic feature was introduced with C# 4.0, Async and Await were introduced with C# 5.0 etc.

In C# 6.0, most focus on syntactical improvement rather than new feature to add on. These features will help us to write code faster and simple way.

So, I am going to explain and after that I hope you will know about delegate and love to use delegate.

Objective

You can download the Visual Studio 2015 or if you have Visual Studio 2013 then you need to download the Roslyn Package from here. Roslyn is the .Net Compiler which is open source and integrated with Visual Studio 2015.

Several new Syntactical Improvement with C# 6.0 has introduced and these are as following;

  1. Using Static
  2. Auto Property Initializers
  3. Index Initializers
  4. String Interpolation
  5. Expression Bodied Members
  6. Getter Only Auto Properties
  7. Exception Filters
  8. Null Conditional Operators
  9. Declaration Expressions

This is very interesting feature which make your coding life easy. Now you can define the class via a using keyword to access the property or method of that classes. Only you need to add static keyword after using and before the namespace of the class.

using static System.Console;

When we define the System.Console class with static in using section then we can access all the properties and methods of System.Console. See the following example where you will see what we do before C# 6.0 and what we can do in C# 6.0.

Before C# 6.0

using System;
namespace CSharp6FeaturesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This is demo for C# 6.0 New Features");
        }
    }
}

Before C# 6.0, if we are going to use the WriteLine() method then we use Console.WriteLine(). WriteLine can not access without the reference of the Console class.

 

In C# 6.0

using static CSharp6FeaturesDemo.MyClass;
namespace CSharp6FeaturesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("This is demo for C# 6.0 New Features");
            Hello();
            ReadLine();
        }
    }
    static class MyClass
    {
        public static void Hello()
        {
            WriteLine("This is static class");
        }
    }
}

C# 6.0 provides the flexibility to use the class without reference of the class everytime. We only need to define it in using statement and we can access it. 

We can also give the references of the other classes to access their members.

  Hello();

In the above example, we can see the Hello() which defined in MyClass. 

static class MyClass
{
   public static void Hello()
   {
       WriteLine("This is static class");
   }
}

Here we only define the namespace in using statement with static keyword as following.

using static CSharp6FeaturesDemo.MyClass;

 

Auto Property Initializer

To access internal members, we use the properties. Properties have their getter and setter. Before C# 6.0, we can not directly define the value of the property. To do this, we basically use the local member variables. But C# 6.0 provides the flexibility to initialise the value.

With C# 6.0, we can directly assign the value of the property at the time of defining the new property.

Before C# 6.0

Earlier we use generally Constructor to initialize the value of the Property. See the following example, here you can see that we have create multiple properties and to initialize the value, constructor will help.

 

using System;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            Console.WriteLine("Employee Id is " + emp.EmployeeId);
            Console.WriteLine("Employee Full Name is " + emp.FullName);
            Console.ReadLine();
        }
    }
    public class Employee
    {
        public Guid EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string FullName { get; set; }
        public Employee()
        {
            EmployeeId = Guid.NewGuid();
            FirstName = "Mukesh";
            LastName = "Kumar";
            FullName = string.Format("{0} {1}", FirstName, LastName);
        }
    }
}

In C# 6.0

But C# 6.0 is very smooth and we don't need to take the tension about how and where we will initialize the vallue of the property. You can directly assign the value of the property after = sign. It will not give you any type of exception and run smoothly. In the below example, we can see that EmployeeId is generating new GUID and also FirstName and LastName are initialized with their values.

using System;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            WriteLine("Employee Id is " + emp.EmployeeId);
            WriteLine("Employee Full Name is " + emp.FullName);
            ReadLine();
        }
    }
    public class Employee
    {
        public Guid EmployeeId { get; set; } = Guid.NewGuid();
        public string FirstName { get; set; } = "Mukesh";
        public string LastName { get; set; } = "Kumar";

        public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }

    }
}

 

Index Initializer

C# 6.0 provides the new way to initialize the collection. You can create index based collections like dictionaries, hashtables etc. As we know that dictionary is the key-value pair and we need to assign the values for their corresponding keys. We have some different way to create the key/value pair before c# 6.0. See the following example how we use the key\value pair for a dictionary object in C# before the C# 6.0.

Before C# 6.0

using System;
using System.Collections.Generic;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> myDictionary = new Dictionary<int, string>() {
                {1, "Mukesh Kumar" },
                {2, "Rahul Rathor" },
                {3, "Yaduveer Saini" },
                {4, "Banke Chamber" }
            };

            foreach (var item in myDictionary)
            {
                Console.WriteLine("The " + item.Key + " Number Employee is " + item.Value + "\n");
            }
            Console.ReadLine();
        }
    }
}

In C# 6.0

But with C# 6.0, we logically define that the value for index 1 is "Mukesh Kumar" and so on. You can see the following example which clears your all doubts.

using System;
using System.Collections.Generic;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> myDictionary = new Dictionary<int, string>()
            {
                [1] = "Mukesh Kumar",
                [2] = "Rahul Rathor",
                [3] = "Yaduveer Saini",
                [4] = "Banke Chamber"
            };

            foreach (var item in myDictionary)
            {
                WriteLine("The " + item.Key + " Number Employee is " + item.Value + "\n");
            }
            ReadLine();
        }
    }
}

 

String Interpolation

For concatenation, we generally use String.Format where we pass the array of the index and then pass the parameters value for it. It is very confuse when you are working with multiple members. C# 6.0 has introduced a very great feature where you don't need to pass the array index, but you can direct pass the your variable but be sure you are using the $ sign before to start. Following is the simple example of getting the full name to use first name and last name. Here we are using the string.Format and after that we need to specify the index array for the parameters value.

Before C# 6.0

using System;
using System.Collections.Generic;

namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            string firstName = "Mukesh";
            string lastName = "Kumar";

            Console.WriteLine("The Full Name of Employee " + string.Format("{0} {1}", firstName, lastName));
            Console.ReadLine();
        }
    }
}

In C# 6.0

using System;
using System.Collections.Generic;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            string firstName = "Mukesh";
            string lastName = "Kumar";

            WriteLine($"The Full Name of Employee {firstName} {lastName}");
            ReadLine();
        }
    }
}

 

Expression Bodied Members

Lambda Expressions are very useful when you are working with Linq query. But in C# 6.0 you can use lambda expressions with properties and functions to increase your productivity and write clean code. 

Using lambda expressions, you can define the method in one line [Use only for simple and short logical methods or properties]. I believe when you are working with large application and you need to get single value based on their condition then there we can use the expression bodied members. We can directly create a function and also get the output based on their parameters values.

 

Before C# 6.0

Earlier we generally use to create a seperate method to complete any simple task, it might be one liner or more than one line. But it was very complex and take time. See the following example where two methods GetFullName and AddTwoNumber are doing simple task like concatenating two string and add two numbers. But to complete this task, we need to write two seperate methods.

using System;
using System.Collections.Generic;

namespace CSharp6FeaturesDemo
{
    public class Program
    {
        public static string GetFullName(string firstName, string lastName)
        {
            return string.Format("{0} {1}", firstName, lastName);
        }
        public static int AddTwoNumber(int firstNumber, int secondNumber)
        {
            return firstNumber + secondNumber;
        }
        static void Main(string[] args)
        {
            string firstName = "Mukesh";
            string lastName = "Kumar";
            int firstNumber = 10;
            int secondNumber = 20;

            Console.WriteLine(GetFullName(firstName, lastName));
            Console.WriteLine(AddTwoNumber(firstNumber, secondNumber));
            Console.ReadLine();
        }
    }
}

In C# 6.0

C# 6.0 does not required to create seperate methods for only single task. It can be defined and completed at that time when it is defining.

using System;
using System.Collections.Generic;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        public static string GetFullName(string firstName, string lastName) => firstName + " " + lastName;
        public static int AddTwoNumber(int firstNumber, int secondNumber) => firstNumber + secondNumber;
        static void Main(string[] args)
        {
            string firstName = "Mukesh";
            string lastName = "Kumar";
            int firstNumber = 10;
            int secondNumber = 20;

            WriteLine(GetFullName(firstName, lastName));
            WriteLine(AddTwoNumber(firstNumber, secondNumber));
            ReadLine();
        }
    }
}

 

Getter Only Auto Properties

When you are working with properties, you need to define the getter and setter both; But in C# 6.0 you can define only the getter for properties. Before C# 6.0 you need to define the both when going to create properties. Sometimes, it is not required to create the setter but we need to define it. But there is not any restriction to make such type of coding with C# 6.0. You can only define the getter for the properties and make it readonly.

See the following example where FirstName and LastName have their getter with their values.

In C# 6.0

using System;
using System.Collections.Generic;

namespace CSharp6FeaturesDemo
{
    public class Program
    {
        string FirstName { get; } = "Mukesh";
        string LastName { get; } = "Kumar";

        public string FullName = string.Empty;
        public Program()
        {
            FullName = FirstName + " " + LastName;
        }
        static void Main(string[] args)
        {
            Program prog = new Program();
            Console.WriteLine("The Full Name is " + prog.FullName);
            Console.ReadLine();
        }
    }
}

 

Exception Filters

It is available with VB but when new compiler "Roslyn" is introduced. This feature added with it. Exception Filter is used to specify the catch block on the basis of some conditional argument. Generally we define only one catch block and inside that we make different conditions for throwing the different types of exceptions. 

But in C# 6.0 you can check the message and show the exception message as per your conditions.

 

Before C# 6.0

using System;
using System.Collections.Generic;

namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            int errorCode = 404;
            try
            {
                throw new Exception(errorCode.ToString());
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("404"))
                    Console.WriteLine("This is Http Error");
                else if (ex.Message.Equals("401"))
                    Console.WriteLine("This is Unathorized Error");
                else
                    Console.WriteLine("This is some different exception");

                Console.ReadLine();

            }

        }
    }
}

In C# 6.0

With C# 6.0, we can check the exception message and on the basis of exception can be defined in catch block. It can be used with multiple catch block and every catch block will be checked with their own condtional message.

using System;
using System.Collections.Generic;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            int errorCode = 404;
            try
            {
                throw new Exception(errorCode.ToString());
            }
            catch (Exception ex) when (ex.Message.Equals("404"))
            {
                WriteLine("This is Http Error");
            }
            catch (Exception ex) when (ex.Message.Equals("401"))
            {
                WriteLine("This is Unathorized Error");
            }
            catch (Exception ex) when (ex.Message.Equals("403"))
            {
                WriteLine("Forbidden");
            }
            ReadLine();
        }

    }
}

You can see that on the basis of the error code the catch block is going to execute.

 

Null Conditional Operators

At the time of coding, we generally check the null value to make some conditions. We check the object is null or not and try to prevent the NullReferenceException. But to do this we need to work some extra code which also makes the code lenghty. 

But with C# 6.0, you don't need to write some extra code, you can use null conditional operator, which is nothing but only a question mark [?] sign.

Before C# 6.0

using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharp6FeaturesDemo
{
    public class Program
    {

        static void Main(string[] args)
        {
            List<Employee> employees = new List<Employee>();
            Program prog = new Program();
            if (employees.FirstOrDefault() != null)
            {
                //This code will not hit because of employees is null;
                Console.WriteLine(employees.First().Name);
            }
            else
            {
                Employee emp = new Employee();
                emp.EmployeeId = 10;
                emp.Name = "Mukesh Kumar";
                emp.Address = "New Delhi";
                employees.Add(emp);
                Console.WriteLine(employees.First().Name);
            }
            Console.ReadLine();
        }
    }
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }

    }
}

In C# 6.0

using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {

        static void Main(string[] args)
        {
            List<Employee> employees = new List<Employee>();
            Program prog = new Program();

            //No need to check null in if condition
            //null operator ? will check and return null if value is not there
            WriteLine(employees.FirstOrDefault()?.Name);

            //set the default value if value is null
            WriteLine(employees.FirstOrDefault()?.Name ?? "My Value");

            ReadLine();
        }
    }
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }

    }
}

See, First value is not going to print anything and also not throwing any error. It is because the ? sign is included with the statement which handle the null exception. And for the second statement the default value "My Value" will be going to print because of the value is null.

 

Declaration Expressions

Using this feature, we don't need to declare the local variable globally we can generally create it inside the expression. But the scope of the variable will be inside the loop where it is defined.

Before C# 6.0

using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            int myValue = 10;
            if (int.TryParse("20", out myValue))
            {
                Console.WriteLine(myValue);
                Console.ReadLine();
            }
        }
    }
}

In C# 6.0

using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
namespace CSharp6FeaturesDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            if (int.TryParse("20", out var result))
            {
                return result;
            }
            return 0; // result is out of scope

            // A new feature in C# 6.0 allows to declare variable inside TryParse method.
            //Declaration expressions was cut from C# 6.0 and wasn't shipped in the final release. 
            //You currently can't do that. There is a proposal for it on GitHub for C# 7.
        }
    }

 

Conclusion

Finally, we have learned about the new features of c# 6.0. It makes our coding life so easy because of this provide the simple way to do complex thing. We need to make habit to adopt it in our daily coding. Hope this will help you to make your code better and clean.

At last thanks for reading this article, hope you enjoyed it. Please give your suggestion and feedback to improve this article through the comment.