Top 10 new features of C# 6.0
– Auto Property Initializer
– Await in a Catch and Finally Block in C#6.0
– Dictionary Initializers in C# 6.0
– Exception Filters in C#6.0
– Expression Bodied Function & Property in C#6.0
– Getter-only Auto Properties in C#6.0
– NameOf Expression in C#6.0
– Null Conditional Operator in C#6.0
– Static Using Syntax in C#6.0
– String Interpolation in C#6.0
http://www.csharpstar.com/top-10-new-features-of-csharp6/
1. Static Using Syntax:
using static System.Console;
namespace CsharpStar
{
class Program
{
static void Main(string[] args)
{
WriteLine("Hello World!");
}
}
}
2. String Interpolation:
class Program
{
static void Main(string[] args)
{
string firstName = "Lana";
string lastName = "Leonard";
WriteLine($"{firstName} {lastName} is my name!");
ReadLine();
}
}
3. Exception Filters:
class Program
{
static void Main(string[] args)
{
var httpStatusCode = 404;
Write("HTTP Error: ");
try
{
throw new Exception(httpStatusCode.ToString());
}
catch (Exception ex)
{
if (ex.Message.Equals("500"))
Write("Bad Request");
else if (ex.Message.Equals("401"))
Write("Unauthorized");
else if (ex.Message.Equals("402"))
Write("Exception Occurred");
else if (ex.Message.Equals("403"))
Write("Forbidden");
else if (ex.Message.Equals("404"))
Write("Not Found");
}
ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
var httpStatusCode = 404;
Write("HTTP Error: ");
try
{
throw new Exception(httpStatusCode.ToString());
}
catch (Exception ex) when (ex.Message.Equals("400"))
{
Write("Bad Request");
ReadLine();
}
catch (Exception ex) when (ex.Message.Equals("401"))
{
Write("Unauthorized");
ReadLine();
}
catch (Exception ex) when (ex.Message.Equals("402"))
{
Write("Exception Occurred ");
ReadLine();
}
catch (Exception ex) when (ex.Message.Equals("403"))
{
Write("Forbidden");
ReadLine();
}
catch (Exception ex) when (ex.Message.Equals("404"))
{
Write("Not Found");
ReadLine();
}
ReadLine();
}
}
5. Null Conditional Operator:
Console.WriteLine(Emp?.Name ?? "Field is null.");
6. Auto Property Initializer:
public class Employee
{
public Guid EmployeeID { get; set; } = Guid.NewGuid();
}
7. Dictionary Initializers:
class Program
{
static void Main(string[] args)
{
var Books = new Dictionary<int, string> ()
{
[1] = "ASP.net",
[2] = "C#",
[3] = "ASP.net MVC5"
};
foreach (KeyValuePair<int, string> keyValuePair in Books)
{
WriteLine(keyValuePair.Key + ": " +
keyValuePair.Value + "\n");
}
ReadLine();
}
}
8. Expression Bodied Function & Property:
class Program
{
private static double AddNumbers
(double num1, double num2)
=> num1 + num2;
static void Main(string[] args)
{
double num1 = 3;
double num2 = 7;
WriteLine(AddNumbers(num1, num2));
ReadLine();
}
}
9. Getter-only Auto Properties:
public DateTime BirthDate { get; }
10. NameOf Expression:
if (newTitle == null) throw new Exception(nameof(newTitle) + " is null");