Microsoft has announced some new keywords and some new behavior of C# 6.0 in Visual Studio 2015.
In this article we will learn the following topics.
- using Static.
- Auto property initializer.
- Dictionary Initializer.
- nameof Expression.
- New way for Exception filters.
- await in catch and finally block.
- Null – Conditional Operator.
- Expression – Bodied Methods
- Easily format strings – String interpolation
For testing all
Open Visual Studio 2015 and select "File" -> "New" -> "Project...".
Click OK and then you will get a solution that you will see in the Solution Explorer.
Now just do something with your program.cs file to test your compile time code.
1. using Static
This is a new concept in C# 6.0 that allows us to use any class that is static as a namespace that is very usefull for every developer in that code file where we need to call the static methods from a static class like in a number of times we need to call many methods from Convert.ToInt32() or Console.Write(),Console.WriteLine() so we need to write the class name first then the method name every time in C# 5.0. In C# 6.0 however Microsoft announced a new behavior to our cs compiler that allows me to call all the static methods from the static class without the name of the classes because now we need to first use our static class name in starting with all the namespaces.
In C# 5.0
In C# 6.0
Code in 5.0
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace TestNewCSharp6
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Enter first value ");
- int val1 =Convert.ToInt32(Console.ReadLine());
- Console.WriteLine("Enter next value ");
- int val2 = Convert.ToInt32(Console.ReadLine());
- Console.WriteLine("sum : {0}", (val1 + val2));
- Console.ReadLine();
- }
- }
- }
Code in C# 6.0
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using static System.Convert;
- using static System.Console;
- namespace Project1
- {
- class Program
- {
- static void Main(string[] args)
- {
- WriteLine("Enter first value ");
- int val1 = ToInt32(ReadLine());
- WriteLine("Enter next value ");
- int val2 = ToInt32(ReadLine());
- WriteLine("sum : {0}", (val1+val2));
- ReadLine();
- }
- }
- }
Now you can see the difference for yourself, there is less code but the output will be the same.
Output
2. Auto property initializer
Auto property initializer is a new concept to set the value of a property during of property declaration. We can set the default value of a read=only property, it means a property that only has a {get;} attribute. In the previous version of C# 5.0 we can set the values of the property in the default constructor of the class. Let's have an example. Suppose we need to set some property's value of a class as in the following:
In C# 5.0
Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace TestNewCSharp6
- {
- class Emp
- {
- public Emp()
- {
- Name = "nitin";
- Age = 25;
- Salary = 999;
- }
- public string Name { get; set; }
- public int Age { get; set; }
- public int Salary { get;private set; }
- }
- }
Here we can set the default value of my property in only by constructors.
In C# 6.0
Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace Project2
- {
- class Emp
- {
- public string Name { get; set; }="nitin";
- public int Age { get; set; }=25;
- public int Salary { get; }=999;
- }
- }
Here we can initialization the default value for the property in the same line.
3. Dictionary Initializer
Dictionary initializer is a new concept in C# 6.0. We can directly initialize a value of a key in a Dictionary Collection with it, either the key in the collection would be a string data type or any other data type. Let's see the declaration syntax in both versions like in C# 5.0 and also in C# 6.0 respectively.
C# 5.0
Code
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace TestNewCSharp6
- {
- class Program
- {
- static void Main(string[] args)
- {
- Dictionary<string, string> dicStr = new Dictionary<string, string>()
- {
- {"Nitin","Noida"},
- {"Sonu","Baraut"},
- {"Rahul","Delhi"},
- };
- dicStr["Mohan"] = "Noida";
- foreach (var item in dicStr)
- {
- Console.WriteLine(item.Key+" "+ item.Value);
- }
- Console.WriteLine("********************************************************************");
- Dictionary<int, string> dicInt = new Dictionary<int, string>()
- {
- {1,"Nitin"},
- {2,"Sonu"},
- {3,"Mohan"},
- };
- dicInt[4] = "Rahul";
- foreach (var item in dicInt)
- {
- Console.WriteLine(item.Key + " " + item.Value);
- }
- Console.Read();
- }
- }
- }
C# 6.0
Code
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Project3
- {
- class Program
- {
- static void Main(string[] args)
- {
- Dictionary<string, string> dicStr = new Dictionary<string, string>()
- {
- ["Nitin"]="Noida",
- ["Sonu"]="Baraut",
- ["Rahul"]="Delhi",
- };
- dicStr["Mohan"] = "Noida";
- foreach (var item in dicStr)
- {
- Console.WriteLine(item.Key + " " + item.Value);
- }
- Console.WriteLine("********************************************************************");
- Dictionary<int, string> dicInt = new Dictionary<int, string>()
- {
- [1]="Nitin",
- [2]="Sonu",
- [3]="Mohan"
- };
- dicInt[4] = "Rahul";
- foreach (var item in dicInt)
- {
- Console.WriteLine(item.Key + " " + item.Value);
- }
- Console.Read();
- }
- }
- }
Here we can initialize the Dictionary values directly by the “=” operator and in C# 5.0 we need to create an object as a {key,value} pair and the output will be the same in both versions.
Output
4. nameof Expression
nameof is new keyword in C# 6.0 and it's very usefull from a developer's point of view because when we need to use a property, function or a data member name into a message as a string so we need to use the name as hard-coded in “name” in the string and in the future my property or method's name will be changed so it must change all the messages in every form or every page so it's very complicated to remember that how many number of times you already use the name of them in your project code files and this avoids having hardcoded strings to be specified in our code as well as avoids explicit use of reflection to get the names. Let's have an example.
We have a class:
And we need to show the values of this class property to the console and also if we need to print the name of my property too with the message so in C# 6.0 we can use the nameof expression rather than hardcode the name of the property.
Output
Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Console;
- namespace Project4
- {
- class Program
- {
- static void Main(string[] args)
- {
- Employee emp = new Employee();
- WriteLine("{0} : {1}", nameof(Employee.Id), emp.Id);
- WriteLine("{0} : {1}", nameof(Employee.Name), emp.Name);
- WriteLine("{0} : {1}", nameof(Employee.Salary), emp.Salary);
- ReadLine();
- }
- }
- class Employee
- {
- public int Id { get; set; } = 101;
- public string Name { get; set; } = "Nitin";
- public int Salary { get; set; } = 9999;
- }
- }
5. Exception filters
Exception filters are a new concept for C#. In C# 6.0 they are already supported by the VB compiler but now they are coming into C#. Exception filters allow us to specify a condition with a catch block so if the condition will return true then the catch block is executed only if the condition is satisfied. This is also a best attribute of new C# 6.0 that makes it easy to do exception filtrations in also that type of code contains a large amount of source code. Let's have an example.
Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Console;
- namespace project5
- {
- class Program
- {
- static void Main(string[] args)
- {
- int val1 = 0;
- int val2 = 0;
- try
- {
- WriteLine("Enter first value :");
- val1 = int.Parse(ReadLine());
- WriteLine("Enter Next value :");
- val2 = int.Parse(ReadLine());
- WriteLine("Div : {0}", (val1 / val2));
- }
- catch (Exception ex) if (val2 == 0)
- {
- WriteLine("Can't be Division by zero ☺");
- }
- catch (Exception ex)
- {
- WriteLine(ex.Message);
- }
- ReadLine();
- }
- }
- }
Output
If all the values are entered by user id correctly then the output will be:
If the user enters an invalid value for division, like 0, then it will throw the exception that will be handled by Exception filtration where you mentioned an if() with catch{} block and the output will be something.
6. Await in catch and finally block
This is a new behavior of C# 6.0 that now we are able to call async methods from catch and also from finally. Using async methods are very usefull because we can call then asynchronously and while working with async and await, you may have experienced that you want to put some of the result awaiting either in a catch or finally block or in both. Let's suppose we need to call a async method and there is a try and a catch{} block so when the exception occurs it is thrown in the catch{} bock. We need to write log information into a file or send a service call to send exception details to the server so call the asynchronous method, so use await in catch{}, this is only possible in C# 6.0. Let's have an example.
We have a class and there is a method that is async and we need to call this with two parameters and if there is an exception then that will we return an exception and will go to the catch{} block and then we will call an async method using await and finally we have called the same in the finally.
7. Null-Conditional Operator
The Null-Conditional operator is a new concept in C# 6.0 that is very beneficial for a developer in a source code file that we want to compare an object or a reference data type with null. So we need to write multiple lines of code to compare the objects in previous versions of C# 5.0 but in C# 6.0 we can write an in-line null-conditional with the ? and ?? operators, so let's have an example and compare both versions, C# 5.0 vs C# 6.0. We will write the code for both version.
8. Expression–Bodied Methods
A Expression–Bodied Method is a very usefull way to write a function in a new way and also very usefull for those methods that can return their value by a single line so we can write those methods by using the “=>“ lamda Operator in C# 6.0 so let's have an example.
We will just write a method in both versions of C# 5.0 vs C# 6.0 with a method that only returns a message of a string value.
9. Easily format strings using String interpolation
To easily format a string value in C# 6.0 without any string.Format() method we can write a format for a string. It's a very usefull and time consuming process to define multiple string values by “\{ variable }”. So let's have an example on String interpolation. First we are writing the source code by string.Format().
Now by “\{variable}”.
Output
The output will be the same in both but by “\{variable}” is a very short way to write the same code.
Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Console;
- namespace Project9
- {
- class Program
- {
- static void Main()
- {
- string FirstName = "Nitin";
- string LastName = "Pandit";
-
-
- string output= "\{FirstName}-\{LastName}";
- WriteLine(output);
- ReadLine();
- }
- }
- }
Thank you for reading this article.
Next article -
List of All New Features in C# 6.0: Part 2