a blog for those who code

Saturday 7 March 2015

New Features in C# 6.0 - Part 2

This post is the continuation of New Features in C# 6.0. The new features in C# 6.0 are String Interpolation, nameof Expressions, Exception Filters, Enhancement to Auto Properties, Null-conditional operators, Expression-bodied methods, Dictionary Initializer and Await in catch and finally blocks.

5. Null-conditional operators

By using this feature developers will definately going to reduce the number of Null Reference Error. Like nullable types, null-conditional operators can be used now. For example, we used to check the object is null or not before calling its properties like

var value = a != null ? a.Prop : null;

But now using Null-conditional operator we can write

var value = a?.Prop; 

The above code will return Prop only when a is not null, otherwise it will return null value.

6. Expression-bodied methods

Expression-bodied methods allow properties, methods, operators and other function members to have bodies as lambda expressions instead of statement blocks. For example, previously we used to write  expressions like

public int FindSqaure(int a)
return a * a;

Now we can rewrite the preceeding example in a single line as in the following

public int FindSqaure(int a) => a * a;

7. Dictionary Initializer

In C# 6.0 you can initialize dictionary in following manner

Dictionary<string, string> dictn = new Dictionary<string, string>
["EMP1"] = "Employee1",
["EMP2"] = "Employee2",
["EMP3"] = "Employee3",
["EMP4"] = "Employee4",

8. Await in catch and finally blocks

In C# 6.0, we can call async operations in catch {} and finally blocks {} by specifying the await keyword. Here is the code snippet

ILogger log = new Logger();
catch(Exception ex){
await log.LogError(ex);
await log.Log("Completed");

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment