X
01Feb

What's New In C# 6.0?

Microsoft has released the preview version of Visual Studio 2015 and .NET 4.6 for developers to try and provide feedback on usage or issues. .NET 4.6 preview comes with C# 6.0 which includes the new additional features expected by developers to improve the coding productivity.

In this article I am going to describe the new features introduced in C# 6.0. If you haven’t download the Visual Studio 2015 please get it from below download button.

Download Visual Studio 2015

Property Initialization with default value

In C# 6.0 we can initialize the default value to property right from the place we create it. With the help of this we can avoid the chances of null errors while accessing property when no value assigned.

Old Style:

        public int Id { get; set; }

        public string FirstName { get; set; }

New Style:

        public int Id { get; set; } = 1001;

        public string FirstName { get; set; } = "Srinivas";

 

String Interpolation

The most common thing we use in our daily coding is String concatenation. For this we use either ‘+’ symbol or string.Format. Sometimes when we use String.Format(), the numbered placeholders like {0}, {1}, {2}, etc. caused the problem (especially when you use more placeholders) due to arguments to be supply in the same order.

This usage is very much simplified in C# 6.0 by adding expression which replaces the numbered placeholders.

Old Style:

name = string.Format("Employee name is {0}, located at {1}", emp.FirstName, emp.Location);

New Style:

name = "Employee name is \{emp.FirstName}, located at \{emp.Location}";

We can even use the expressions in the content placeholder area as below:

name = "Employee name is \{emp.FirstName}, located at \{emp.Location}. Age of employee is \{(emp.Age > 0) ? emp.Age.ToString() : "N/A"}";

Note: The above syntax works well in preview, however Microsoft has decided to change the syntax even in much better way as below:

name = $"Employee name is {emp.FirstName}, located at {emp.Location}";

 

Expression Bodied Functions

C# 6.0 allows properties, methods and other members to have bodies as lambda expressions instead of statement blocks. This will reduces the little lines of codes and gives clear view.

Old Style:

        public string[] GetCountryList()

        {

            return new string[] { "India", "USA", "UK" };

        }

New Style:

        public string[] GetCountryList() => new string[] { "India", "USA", "UK" };

 

Import Static Classes

We know that static members can only be accessed by only class name and can’t be instantiate for static classes. If your class is having more static members and you need to repeat the class name all the times whenever you are calling static member. It is redundant, which is not necessary.

C# 6.0 allows us to import the Static classes and use the static members directly without class name. For instance, Math is a core static class from .NET library. Before C# 6.0 we must call its methods with class name. But now things makes simpler by importing Math class with using statement and call mathematical functions directly as shown below:

Old Style:

            double powerValue = Math.Pow(2, 3);

            double roundedValue = Math.Round(10.6);

New Style:

            using System.Math;

            double powerValue = Pow(2, 3);

            double roundedValue = Round(10.6);

Same implementation can be used for calling extension methods as shown below: (assume you have a list object for employee collection)

Old Style:

            var employees = listEmployees.Where(i => i.Location == "Bangalore");

New Style:

            using System.Linq.Enumerable;

            var employees = Where(listEmployees, i => i.Location == "Bangalore");

 

Null-conditional operators

C# 6.0 introduces Null-conditional (?.) operator which works on top of conditional (?:) operator to provide the much easier access to check the NULL values.

It returns null value, if any of the object in the series of reference objects provided is null. The new style will also reduce the code when you use nested conditions.

            var emp = new Employee()

            {

                Id = 1,

                Age = 30,

                Location = "Bangalore",

                Department = new Department()

                {

                    Id = 1,

                    Name = "IT"

                }

            };

Old Style:

            string location = emp == null ? null : emp.Location;

            string departmentName = emp == null ? null : emp.Department == null ? null : emp.Department.Name;

New Style:

            string location = emp?.Location;

            string departmentName = emp?.Department?.Name;

 

nameof Expressions

In C# 6.0, nameof operator will be used to avoid the hardcoded string laterals which may causes spell mistakes especially when we work with PropertyChanged() in XAML. It accepts an element as parameter and returns the string lateral for the same element. The parameter can be any member like property, method, class, etc.

            var emp = new Employee()

            {

                Id = 1,

                Age = 30,

                Location = "Bangalore",

                Department = new Department()

                {

                    Id = 1,

                    Name = "IT"

                }

            }; 

            Response.Write(emp.Location); //result: Bangalore

            Response.Write(nameof(Employee.Location)); //result: Location

 

Await in catch and finally blocks

Most of the times we use catch and finally blocks to log exceptions, sending exception notifications and cleaning up the resources. Before C# 6.0, these catch and finally blocks wouldn’t allow the await for async operations due to compiler limitations. Developers has to found their own workaround solutions on this

Now C# 6.0 allows us to use await statement in catch and finally blocks for asyc operations.

        public async Task StartAnalyzingData()

        {

            try

            {

                // collect and analyze the data               

            }

            catch

            {

                await LogExceptionDetailsAsync();

            }

            finally

            {

                await CloseResourcesAsync();

            }

        }

 

Exception Filters

Exception Filters (conditional exceptions) are the CLR capability which is already available in Visual Basic, but not in C# till now.

In order to use it, you must be declare the condition on the same line where the Catch block was defined like catch (Exception ex) if (filterCondition). If the filter condition is true, then only the Catch block will execute else it will skip from the execution.

            try

            {               

                //throw some exception here for test

            }

            catch (ArgumentNullException ex) if (ex.Source == "EmployeeCreation")

            {

                //notify null exception

            }

            catch (InvalidOperationException ex) if (ex.InnerException != null)

            {

                //notify and log exception

            }

            catch (Exception ex) if (ex.InnerException != null)

            {

                //log general exception

            }

 

Dictionary Initializer

C# 6.0 adds the ability to add values of the dictionary to its keys/indexes directly while initializing itself. The common use of this is, creating a Json object at one time instead creating an object first and assigning the values later on.

            var country = new Dictionary<int, string>

            {

                [0] = "India",

                [1] = "USA",

                [2] = "UK",

                [3] = "Japan"

            };

 

C# 6.0 with code name Roslyn, made with many syntactical changes and along with that introduced other new features. Also Microsoft has improved the C# compiler with new core and performance level technologies.

Happy coding!!! J

 

Related

Deploy .NET application on IIS using GitHub actions

In this blog I will be showing how to deploy a .net application on IIS server (self-hosted runner). ...

Read More >

NAV – Connecting Microsoft Dynamics CRM customized entities

This blog is intended to see how Microsoft Dynamics NAV (here onwards NAV) can be connected to exter...

Read More >

NAV – Connecting External SQL

This blog is intended to see how Microsoft Dynamics NAV (here onwards NAV) can be connected to exter...

Read More >

What are Frames? How to handle frames in Selenium WebDriver with C#?

IFrame (FullForm: Inline Frame) is an HTML document that is included in another HTML document and is...

Read More >

What is Synchronization? Handling Synchronization in Selenium WebDriver using C#:

Synchronization meaning: when two or more components involved to perform any action, we expect these...

Read More >

How to Prevent Users from Moving Task to Closed State with a non-Zero value Remaining Work field in VSTS/TFS

In this Blog I am going to explain how we can customize Task in VSTS/TFS to Prevent Users from Movin...

Read More >

Sending Test reports by Email using Office 365, Gmail

Wouldn’t it be great if Test Report are sent automatically across team as soon the Test Execut...

Read More >

Token Based Authentication for Web API's

Securing ASP.NET Web API using Custom Token Based AuthenticationProviding a security to the Web API&...

Read More >

Canarys Automations Pvt Ltd recognized as finalist for 2017 Microsoft DevOps Partner of the Year Award

  Bengaluru, Karnataka, India — June 2, 2017 — Canarys Automations Pvt Ltd tod...

Read More >

Custom Control in WPF

File Upload Custom Control in WPFThis article is about Custom control in WPF, Custom controls are al...

Read More >

Share

Post a Comment

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Text/HTML
Text/HTML
Contact Us
  • *
  • *