List of All New Features in C# 6.0
Microsoft has announced some new keywords and some new behavior of C# 6.0 in Visual Studio 2015.
- 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
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 useful 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.
using System;
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("Value is : {0}", (val1));
ReadLine();
}
}
}
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.
class Emp
{
public string Name { get; set; }="nitin";
public int Age { get; set; }=25;
public int Salary { get; }=999;
}
4. nameof Expression
nameof is new keyword in C# 6.0 and it's very useful 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.
nameof Returns the name of property in below code.
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 the 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.
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();
}
}
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 useful 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.
public class MyMath
{
public async void Div(int value1, int value2)
{
try
{
int res = value1 / value2;
WriteLine("Div : {0}", res);
}
catch (Exception ex)
{
await asyncMethodForCatch();
}
finally
{
await asyncMethodForFinally();
}
}
private async Task asyncMethodForFinally()
{
WriteLine("Method from async finally Method !!");
}
private async Task asyncMethodForCatch()
{
WriteLine("Method from async Catch Method !!");
}
}
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
class Program
{
static void Main()
{
Employee emp = new Employee();
emp.Name = "Rahul Kumar";
emp.EmployeeAddress = new Address()
{
HomeAddress = "Lucknow",
OfficeAddress = "Kanpur"
};
WriteLine((emp?.Name) + " " + (emp?.EmployeeAddress?.HomeAddress??"No Address"));
ReadLine();
}
}
8. Expression–Bodied Methods
An Expression–Bodied Method is a very useful way to write a function in a new way and also very useful 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
class Program
{
static void Main(string[] args)
{
WriteLine(GetTime());
ReadLine();
}
static string GetTime()=> "Current Time - " + DateTime.Now.ToString("hh:mm:ss");
public int Compare(int a, int b) => a == b ? 100 : 200;
// Method that call another method
public void called() => Display();
}
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 using interpolation
class Program
{
static void Main()
{
string FirstName = "Dotnet";
string LastName = "Guru";
// With String Interpolation in C# 6.0
string output= "\{FirstName}-\{LastName}";
WriteLine(output); // Dotnet-Guru
ReadLine();
}
Reference: https://www.c-sharpcorner.com/
0 comments:
Post a Comment