In every version of C#, new language specific features are introduced. Certain features withstand the time and some features are left un-noticed by the developer community over the period of time. In this article I have listed some of the new features that are available in C# 6
Auto property Initializer
The auto property initializer helps to assign the default the value while at the property declaration itself.
public int No { get; set; } = 10;
public string Title { get; } = "C# 6.0";
Expression-bodied members
Expression-bodied function members used to allow the properties, methods to have bodies as lambda.
public int sum(int a, int b)
{
return a + b;
}
This method can written with an expression to avoid the block of statement
public int sum(int a, int b) => a + b;
public string FullName => FirstName + "-" + LastName;
Import of static type members into namespace
The using namespace (using System) will reduce the redundant “System” prefixes in the code. The using static used to access the static members of the class directly without their class name.
using static System.Console;
using static System.Math;
class Program
{
static void Main(string[] args)
{
WriteLine("Sqrt(4) : " + Sqrt(4));
}
}
Exception filters
Exception filters allow you us to specify the condition clause for each catch block. The catch block will try to match the type of exception and evaluate the condition.
try
{
}
catch (NullReferenceException ex) when(DateTime.Now.DayOfWeek != DayOfWeek.Sunday)
{
Log("Weekdays" + ex.Message);
}
catch (Exception ex) when(ex.Message=="User Exception")
{
Log(ex.Message);
}
catch(Exception)
{
}
Nameof operator
Most of the cases we are reusing the name of a property/variable, when throwing an exception message based on the variable name, or handling a PropertyChanged event.
private void Open(int timeout)
{
if (timeout > 180)
throw new ArgumentOutOfRangeException(nameof(timeout) + ” is invalid”);
}
private int discount;
public event PropertyChangedEventHandler OnPropertyChanged;
public int Discount
{
get
{
return discount;
}
set
{
discount = value;
OnPropertyChanged(this,
new PropertyChangedEventArgs(nameof(Discount)));
}
}
Null-conditional operators
C# 6.0 includes a new null-conditional operator that helps us to check the null values without adding an if conditional or conditional operator.
if (emp != null && emp.detail != null)
{ firstName = emp.detail.DisplayName; }
Using Null-Conditional Operator
firstName = emp?.detail?.DisplayName;
Dictionary initializer
The dictionary initializer approaches the same way as key and value, but the key as indexer which makes the code more readability.
Dictionary<int, Employee> dict = new Dictionary<int, Employee>()
{
[1] = new Employee("First", "Last"),
[2] = new Employee("First", "Last"),
};
Await in catch/finally blocks
Now It is possible to use the await keyword in catch and finally blocks. In many scenarios the exceptions logs may be in service call as an async method and often we may perform the cleanup with async in finally clause.
try
{
}
catch (Exception ex)
{
await LogAsync(ex.Message);
}
String Interpolation
String Interpolation used to display the expressions directly in the string literal in a formatted manner.
string displayName = $"Welcome {firstName} - {lastName}";
WriteLine(displayName);
WriteLine($"Price is {price:n}");
WriteLine($"Price : {(price < 250 ? 250 : price)}");
Extension Add methods in collection initializers
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(string first, string last)
{
FirstName = first;
LastName = last;
}
}
public static class Dic
{
public static void Add(this Dictionary<string, Person> dic, Person person)
{
dic.Add(Guid.NewGuid().ToString(), person);
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, Person> dic = new Dictionary<string, Person>() {
new Person("one","two"),new Person("first","second")
};
foreach (var d in dic)
{
WriteLine(d.Key + " is " + d.Value.FirstName);
}
}
}
Leave a comment