Wednesday, April 29, 2015

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 withC# 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 { getset; }
        public string FirstName { getset; }
New Style:
        public int Id { getset; } = 1001;
        public string FirstName { getset; } = "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<intstring>
            {
                [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

No comments:

Post a Comment

Get files of last hour in Azure Data Factory

  Case I have a Data Factory pipeline that should run each hour and collect all new files added to the data lake since the last run. What is...