Click here to Skip to main content
15,900,461 members
Articles / Programming Languages / C#
Tip/Trick

New Features C# 6.0

Rate me:
Please Sign up or sign in to vote.
4.44/5 (6 votes)
31 Dec 2014CPOL2 min read 30.4K   5   8
Tip about newly introduced features in C# 6.0 and some of them are improved which were existing in an earlier version of C#.

Introduction

I would like to give a quick understanding about the C# 6.0 features which are newly introduced and improved feature which were being used in the earlier version of C# along with simple code example.

Using the Code

(i) Auto Property Initialization

It is improved & very easy for all developers now. We can initialize auto property while defining itself.

For example:

C#
public sting DeptName 
{ get;set;} = "Engineering";

If we want to initialize Read-Only auto property, we can do it either in property definition or constructor.

First way, (while defining property):

C#
public string CustomerName
{ get; } = "Rajan" ; 

Second way, (in constructor):

C#
public string CustomerName
{  get;  }

public Customer(string name)
{
   this.CustomerName = name;
}

(ii) "nameof()" Operator

Earlier:

C#
private string deptname;
public string DeptName
{ 
  get {return deptname;}
  set {
        deptname =value;
        OnPropertyChanged("DeptName");
      }
}

nameof(propertyname) returns string lateral for the given propertyname.

C#
private string deptname;
public string DeptName
{ 
  get {return deptname;}
  set {
        deptname =value;
        OnPropertyChanged(nameof(DeptName)); // Retrieves the string lateral 
      }
}

(iii) Await Usage in Catch (or) Finally Block

C#
List<MyLog> logs=new List<MyLog>();
try
{
   logs=await GetMyLogs();
}
catch(Exception ex)
{
   await GetExceptionLogs(logs,ex);
}
finally
{
   if(logs!=null)
      await CloseAllLogs();
}

Now, we will be able to use await keyword inside catch / finally block also. Earlier, it was restricted to use only in try block.

(iv) Exception Filter

Syntax

C#
try
{}
catch(Exception ex) if(condition)
{
  // Handing Exception 
}

Example

C#
try { }
catch(Exception ex) if(e.InnerException != null)
{
  //Handling exception
}

The “if” condition should be before the open parenthesis of catch() block. Catch block will be executed only when if loop returns true, else it will move on to next statement or catch(), if we have one more.

(v) Expression Bodied Members

If we’re having read-only property, method and user defined operators, where the method body has a expression like single return statement, then we can use this feature like lambda expression.

We can use “=>” instead parenthesis only when there is a single return statement.

If we consider, OrderName is the read-only property and product order (private field) is the member of the Product class, then we can write like below:

C#
public string OrderName => this.productOrder;

private void Display() => WriteLine("Hi This is superb feature..");

Here, this is not a lambda expression.

(vi) Null Propagation

If we say, Person class has Address property, then person (p) is the instance of Person class. Earlier, we followed the way given below:

C#
if (p != null && p.PersonAddress != null)
    var state=p.PersonAddress.State;

Now null checking is very easy by using (?.):

C#
var address= p?.p.PersonAddress?? 
"Has no data"; // If p is null, then it returns "Has no ata" statement

(vii) String Interpolation

The below improved version of string interpolation works only in the preview of Visual Studio 2015. In a later release, there may be a change in this feature.

Earlier:

C#
Console.WriteLine("{0}", person.Name); 

Now:

C#
WriteLine("\{person.Name}");

We will be able to use alignment and format specifier as well:

C#
var s = "\{p.Name,20} is \{p.Age:D3} year{s} old";

Directly, we will be able to use property name inside the braces.

(viii) Dictionary Initializer

Earlier:

C#
Dictionary<string, string> dictionaryInitializer = new Dictionary<string, string>()
                                                   {
                                                     {"Label Text", "Enter Name"},
                                                     {"Button Content", "Click to Go"}
                                                   };

But now:

C#
Dictionary<string, string> dictionaryInitializer = new Dictionary<string, string>()
    {["Label Text"] ="Enter Name",["Button Content"] ="Click to Go"};

The above code helps to initialize not only members but also indices of newly created object.

(ix) Using Static Members

Through this feature, we can import static members of type into project and custom type static can also be imported.

Remember one thing, this feature is only apt for members of static type.

Well known example:

C#
using System;

int a=45;
Console.WriteLine(Math.Tan(a)); 

Changed to:

C#
using System.Console;
using System.Math;

int a=45;
WriteLine(Tan(a)); 

Hope this feature will make developers' life very easy.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Simple Concept for achieving anything "Practice... Practice... Practice..." will make you stronger irrespective of the background of person!!!".

Comments and Discussions

 
GeneralMy vote of 1 Pin
Gold$Coin1-Jan-15 16:15
professionalGold$Coin1-Jan-15 16:15 
GeneralRe: My vote of 1 Pin
Vaso Elias5-Jan-15 23:44
Vaso Elias5-Jan-15 23:44 
Actually it is Smile | :) Maybe Microsoft should call it 5.1 Smile | :)
GeneralRe: My vote of 1 Pin
Gold$Coin6-Jan-15 15:44
professionalGold$Coin6-Jan-15 15:44 
GeneralRe: My vote of 1 Pin
AnneTheAgile8-Jan-16 6:17
AnneTheAgile8-Jan-16 6:17 
Questioncan we define property indexer in c#? Pin
Sid_Joshi31-Dec-14 21:49
professionalSid_Joshi31-Dec-14 21:49 
AnswerRe: can we define property indexer in c? Pin
K K Srinivasan3-Jan-15 17:26
K K Srinivasan3-Jan-15 17:26 
GeneralRe: can we define property indexer in c? Pin
Sid_Joshi4-Jan-15 18:21
professionalSid_Joshi4-Jan-15 18:21 
GeneralRe: can we define property indexer in c? Pin
K K Srinivasan4-Jan-15 19:52
K K Srinivasan4-Jan-15 19:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.