C# 6.0 New Features

In this blog, we will learn new features of C#6.0. C# 6.0 - An another version of C# released in the year 2015. C# 6 provides numerous new features but I will write about those features which I have explored and which are useful for a developer. You must be curious to know about What's new in C# 6.0? Let's start.

Here are top 8 new features of C# 6.0

Roslyn, a new compiler introduced in C# 6.0. There are various features introduced in C# 6.0. But from programming context below are useful 8 features. Let's explore the list of new features in C# 6.
  1. Auto Property Initializers
  2. using static
  3. Null Conditional Operator
  4. Exception Filters
  5. await in Catch and Finally block
  6. index initializers
  7. Expression Bodied functions
  8. String Interpolation

1. Auto Property Initializers

It allows you to set an initial value for auto initializer. In earlier C# version this feature was not available.
Below is the code snippet.

public class Customer1
    {
        public Guid customerID1 { get; set; } = Guid.NewGuid();
    }

2. using static

This is one of the interesting features of C# 6.
It allows you to import the static methods of a single class.
for eg -
instead of writing using System;
We can now write.

using static System.Console;
using static System.Math
See below code snippet.

using static System.Console;

            //Before C# 6.0
            Console.WriteLine("Hello");

            //After C# 6.0
            WriteLine("Welcome to C#"); 
            ReadLine();


3. Null-Conditional Operator

NULL Reference error always threatens to the developer. In C# 6.0 new version life is easy and it doesn't throw NULLReferenceException error. Please check below code snippet.

            Product objProduct = new Product();
            if (string.IsNullOrEmpty(objProduct.ProductName))
            {
                objProduct = null;
            }
                          // Before C# 6.0
            WriteLine(objProduct != null ? objProduct.ProductName : "Product1"); 
                          // from C# 6.0 onwards
            WriteLine(objProduct?.ProductName ?? "Product2"); 


public class Product
    {
        public string ProductName { get; set; } = string.Empty;
    }



4. Exception Filter

I personally love this new feature of C# 6. Exception filter allows you to show/log different exception messages based on your choice or requirement.

For eg - You want to show different exception messages to your internal and external users. How you will achieve this. Before C# 6.0 it was not possible, but now in C# 6.0, this feature allows you to do the same.

Please see below code snippet.

            string user1 = "user";
            string user2 = "admin";
            string loggedinUser = string.Empty;
            try
            {
                if (loggedinUser == user1)
                {
                    //Some action
                    //Exception occurred
                }

                else if (loggedinUser == user2)
                {
                    //Some action
                    //Exception occurred
                }
            }

            catch(Exception ex) when(loggedinUser == user2) // This exception for admin
            {
                WriteLine("Hi, There is some issue. Please contact super admin.");
            }

            catch(Exception ex)// This exception for other users
            {
                WriteLine("Hi, There is some issue. Please contact administrator");
            }

5. await in catch and finally block

C# 6.0 new feature provides asynchronous programming in catch and finally

This is the most awaited feature. Before c# 6.0 it was not possible to use async and await within catch and finally block. But now it is possible in C# 6.0. Please look at below code snippet.

        //Asynchronous programming in catch finally
        public async void CalCDevision(int val1, int val2)
        {
            try
            {
                int res = val1 / val2;
                WriteLine(res);
            }
            catch (Exception)
            {

                await CatchMethod();
            }
            finally
            {
                await FinallyMethod();
            }
        }

        private async Task CatchMethod()
        {
            WriteLine("Exception occured");
        }

        private async Task FinallyMethod()
        {
            WriteLine("Finally Executed");
        }

6. Index Initializer

This C# 6.0 feature makes collection initializers more consistent.
Before C# 6.0 Dictionary Initialization syntax is {"Key", "Value"}
But now in C# 6.0 we can write like this - ["Key"] = "Value";

See below code snippet.

          //Dictionary initialization Before C# 6.0

            var WebPageError = new Dictionary<int, string> {
            { 404, "Page Not Found" }, { 301, "Moved Permanently" },{ 404, "Internal Server Error" }};

            //After C# 6.0
            var webPageError = new Dictionary<int, string>
            {
                [404] = "Page Not Found",
                [301] = "Moved Permanently",
                [500] = "Internal Server Error"
            };

7. Expression-Bodied Function

This C# 6.0 new feature allows us to write a function as an expression. See below code snippet and you will notice the differences.

       //Before C# 6.0
        public static int AddNumbers(int x, int y)
        {
            return x + y;
        }

        //C# 6.0 onwards
        public static int Add2Numbers(int x, int y) => x + y;

8. String Interpolation

With this new feature of C# 6.0 way to write Format string has been completely changed. See below code snippet.

            string message = "Hi {0}, Welcome to {1}.";
          string userName = "User";
          string sitename = "SharePointCafe.net";
            //Before C# 6.0
            string output = string.Format(message, userName, sitename);
          WriteLine(output);

            //C# 6.0
            message = $"Hi {userName}, Welcome to {sitename}.";
          WriteLine(message);
          ReadLine();

If you want to watch the steps to implement top C# 6.0 new features, then watch videos on youtube.

You may watch below videos - C# 6.0 new Features Part1 and Part2






You may also like other blogs:
Introduction to .Net Core 2.0
SharePoint 2013 Server Object Model

Comments

Popular

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners