Here is a welcome post for the C# 6.0. I am hereby sharing altogether what are all I have read. And I have given some easily understandable sample code snippets.
Lets look at the new features of C# 6.0.
Primary Constructors:
Primary Constructor feature allows you to mention the
arguments of the constructor while creating the class itself. Please find the
code below:
Class Employee(string name, int id)
{
private string _name = name;
private int _id = id;
}
And if you have more than one constructor, then you can
define them as usual, but only one is primary and the one declared along with
class creation is the primary constructor.
for ex:
Class Employee(string name, int id)
{
private string _name = name;
private int _id = id;
public Employee(string name, int id, string platform)
{
//your code
}
}
In this, still the constructor with 2 parameters is the primary constructor.
Auto Properties:
You have a new way of defining your default value to your
property. In the below code, for the class Employee, we have the properties
name and id, to which we are setting default values.
Class Employee
{
Public string name { get; set; } = “Karuppasamy”;
Public int id {get; set; } = 1552;
}
Class Syncfusion
{
Employees.Add (new Employee(){ name, id}); à The default value will
be set to the property
}
Using Statement for Static members:
No more need to use the class name repeatedly as prefix
while calling the static member of a class. You can declare the class in the
using as below,
Using MyNameSpace.MyClass;
Class Employee(string name, int id)
{
Private string _name = name;
Private int _id = id;
WriteProperties(_name, _id); à consider MyClass
contains the static method WriteProperties.
}
Declaration Expression:
No more need to declare the out variable before it is been
used.
Lets have this method:
CalculateExperience(int YearofJoin, out int experience)
{
experience = DateTime.Now.year – YearofJoin;
}
Current expression to call this method as follows:
we need to declare the out variable before pass it to method
int experience;
CalculateAge(2012, out experience);
We can call this method in C# 6.0 as follows
CalculateAge(2012, out var experience);
Using Await in a catch/finally block.
The compiler will allow you to use await inside the catch
block and obviously in finally block too.
Ex: if you are about to download from URL and if it is
broken, you can give another URL in the catch block. Find the code below:
WebClient wc = new WebClient();
String result;
Try
{
result = await wc.DownloadStringTaskAsync(new Uri (http://brokenUri));
}
Catch
{
result = await wc.DownloadStringTaskAsync(new Uri (http://SpareUri));
}
Null Propagation:
You would have done the following code to add the Null
Check.
Console.Write(Employee == null ? “No Employee” : Employee.Id);
But in C# 6.0, the above code has been shortened as
Console.Write(Employee.Id ?? “No Employee”);
Kindly leave your valuable comments and feedback.
Thanks,