Menu

Showing posts with label Visual Studio 2015. Show all posts
Showing posts with label Visual Studio 2015. Show all posts

Sunday, 30 November 2014

Literals and Seperators in C# 6.0


This feature is very helpful to write more readable code while initializing properties and variables for numerical values with new syntax for byte and long types.

Binary:
The new syntax for declaring binary property now, you can use 0b as a prefix.
public byte BinaryCode {get; } =  0b1010; 

Long:
The new syntax for declaring long type property to provide ability to use underscore (_) as a separator. Its much easier to look at the value like billions or millions etc.
public long Number {get; } = 1_000_000_000;

Exception Filters in C# 6.0


This feature helps to filter the exception messages by providing conditional statements which returns true or false at catch block.

Suppose, if you want to log the exception in catch block only if inner exception is not null. In that scenario, you can write the code like the below.
 So, In the catch block if condition returns true then it enters into the catch block and it would log and throws the exception.
try  
{  
   //Some Exception Throws  
}  
catch(Exception ex) if(ex.InnerException != null)  
{  
   //Log the Exception and throw  
   throw;  
}  
finally  
{  
}  

Conditional Access in C# 6.0

This feature is very helpful to use in a scenario like to get the property value from the object only if object is not null.
For Example, you are considering delegate Action as the parameter to any of the method, You want to get the name from the Action Method only if Action is not null and Action.Method is not null.
You can easily get an idea by just looking the below code.

public void LogAction(Action action)  
{  
    //Before C# 6.0  
    var actionName = "Empty";  
    if (action != null && action.Method != null)  
    {  
        actionName = action.Method.Name;  
    }  
  
    //C# 6.0  
    var actionName = action?.Method?.Name ?? "Empty";  
  
}  


As per the above code in C# 6.0, action is not null and Method is not null then only "Name" property value is assigned otherwise "Empty" value will be assigned.