New features introduced in C# 5.0 or less are async and async/await, dynamic keyword, linq and so on. As such there are no major changes in C# 6.0 some syntactical improvements.
Auto property initializers
This feature enables you to assign a default value for a property as part of the property declaration. In C# 5.0 we use constructor to set a default value.
public class Person { public string FirstName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty; public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } } }
Expression bodied members
The lambda expression => here is use to set value like
public string FullName => string.Format("{0} {1}", FirstName, LastName);
Or setting given expression body functions as below
public TimeSpan GetAge() => DateTime.Now - BirthDate;
Getter-only auto-properties
While creating immutable property you can omit set accessor to create a readonly property.public DateTime BirthDate { get; }
String interpolation
A new feature named string interpolation where string.Format call is replaced by a $ sign. Followed by array of values. Syntax is:
public string FullName => $"{FirstName} {LastName}";
Null coalescing operator - ??
This will replace if else statement with one-line conditional operator (??) checking null values and setting some default value.
var someValue = service.GetValue(); var defaultValue = 23 //result will be 23 if someValue is null var result = someValue ?? defaultValue;
Null-conditional operators
Getting NullReferenceException while referencing a member of an object. Place a null conditional operator (?) just before member you want to reference.
var people = new List<Person>(); var name = people.FirstOrDefault()?.FullName;
Async /Await Pattern
Use the async/await pattern to allow execution of a current method while waiting for a asynchronous task to complete. Example of using async/await is while downloading a file using httpClient making a web request.
public async Task TestMethodAsync() { Task<int> longRunningTask = LongRunningOperationAsync(); // call await on the task int result = await longRunningTask; Console.WriteLine(result); } public async Task<int> LongRunningMethod() // assume we return an int from this long running operation { await Task.Delay(1000); // 1 second delay return 1; }
Object / array / collection initializers
Create instances of classes, arrays and collections easily by using the object, array and collection initializers:
public class Employee { public string FirstName {get; set;} public DateTime LastName {get; set;} } //Create an employlee by using the initializer Employee emp = new Employee {FirstName="Shabbir", LastName="Ahmed"};
The above example can be really useful in unit testing but should be avoided in other contexts as instances of classes should be created using a constructor.
Operator: as and is
The is-operator is used to check or control if an instance is of a specific type.
if (obj is Person) { //do some stuff }
Use the as-operator while trying to cast an instance of a object to a particular class. It will return null if cast was not possible:
var emp = person as Person; if (emp != null) { //do some stuff }
Yield-keyword
The yield-keyword lets you return an IEnumerable<T> interface from a method. The following example will return each powers of 2 up to the exponent of 8.
public static IEnumerable<int> Power(int number, int exponent) { int result = 1; for (int i = 0; i < exponent; i++) { result = result * number; yield return result; } }
yield return adds one item to the returned IEnumerable<T> each time it is called. yield return can be very powerful as it enables you to lazily generate a sequence of objects or collection.