Skip to main content

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.




1.Auto 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";

2. 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}";

3. 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" };

4. 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");

5. 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;

6. 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


7. 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();
            }
        }
8. 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
            }

9. 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"
            };


10 . Parameter Less Struct Constructor

With C# 6.0 we can have a parameter less contractor for structures, which was not possible earlier.

  Struct Student
  {
  int  age;
  Student()
  {
  age = 5;
  }
  }

11. Declaration expressions

This feature simply allows you to declare local variable in the middle of an expression. It is as simple as that but really destroys a pain. I have been doing a lot of asp.net web form projects in the past and this was my every day code:


long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{
}
which can be improved to this:

if (!long.TryParse(Request.QureyString["Id"], out long id))
{
}

The scoping rules for this kind of declaration is same as general scoping rules in C#. 

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.

Comments

Popular posts from this blog

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {          Re=re;          Im=im;      } } As we know this structure consumes about 16

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitations.

How to allow a very large object in .net application?

Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio, and create C# Console Application. Lets create simple struct with two double members like example below: public struct ComplexNumber { public double Re; public double Im; public ComplexNumber(double re, double im) { Re = re; Im = im; } } As we know this structure consumes about 16 bytes of memory. So if we want to create array of this type which consume more than 2GB we need to create array at least with 134217728 instances. So this sample program below creates 130000000 (about 1,97 GB) of array. int maxCount = 130000000; ComplexNumber[] arr = null; try { arr = new ComplexNumber[maxCount]; } catch (Exception ex) { Console.WriteLine(ex.Message); } So if we run t