Click here to Skip to main content
15,881,559 members
Articles / Programming Languages / C# 6.0

New Features in C# 6.0

Rate me:
Please Sign up or sign in to vote.
4.76/5 (20 votes)
9 Feb 2015CPOL3 min read 63.8K   17   6
This post covers the new features in C# 6.0

This post covers what are the new language features in C# 6.0. Also a new compiler has been introduced code name “Roslyn”. The compiler source code is open source and can be downloaded at the Codeplex site from the following link https://roslyn.codeplex.com/.

List of New Features in C# 6.0

We can discuss about each of the new features, but first, below is a list of few features in C# 6.0:

  1. Auto Property Initializer
  2. Primary Consturctors
  3. Dictionary Initializer
  4. Declaration Expressions
  5. Static Using
  6. await inside catch block
  7. Exception Filters
  8. Conditional Access Operator to check NULL Values

1. Auto Property Initialzier

Before

The only way to initialize an Auto Property is to implement an explicit constructor and set property values inside it.

C#
public class AutoPropertyBeforeCsharp6
{
    private string _postTitle = string.Empty;
    public AutoPropertyBeforeCsharp6()
    {
        //assign initial values
        PostID = 1;
        PostName = "Post 1";
    }

    public long PostID { get; set; }

    public string PostName { get; set; }

    public string PostTitle
    {
        get { return _postTitle; }
        protected set
        {
            _postTitle = value;
        }
    }
}

After

In C# 6, auto implemented property with initial value can be initialized without having to write the constructor. We can simplify the above example to the following:

C#
public class AutoPropertyInCsharp6
{
    public long PostID { get;  } = 1;

    public string PostName { get; } = "Post 1";

    public string PostTitle { get; protected set; } = string.Empty;
}

2. Primary Constructors

We mainly use constructor to initialize the values inside it. (Accept parameter values and assign those parameters to instance properties).

Before

C#
public class PrimaryConstructorsBeforeCSharp6
{
    public PrimaryConstructorsBeforeCSharp6(long postId, string postName, string postTitle)
    {
        PostID = postId;
        PostName = postName;
        PostTitle = postTitle; 
    }

    public long PostID { get; set; }
    public string PostName { get; set; }
    public string PostTitle { get; set; }
}

After

C#
public class PrimaryConstructorsInCSharp6(long postId, string postName, string postTitle)
{        
    public long PostID { get;  } = postId;
    public string PostName { get; } = postName;
    public string PostTitle { get;  } = postTitle;
}

In C# 6, primary constructor gives us a shortcut syntax for defining constructor with parameters. Only one primary constructor per class is allowed.

If you look closely at the above example, we moved the parameters initialization beside the class name.

You may get the following error “Feature ‘primary constructor’ is only available in ‘experimental’ language version.” To solve this, we need to edit the SolutionName.csproj file to get rid of this error. What you have to do is we need to add additional setting after WarningTag.

XML
<LangVersion>experimental</LangVersion>

Feature 'primary constructor' is only available in 'experimental' language version

Feature ‘primary constructor’ is only available in ‘experimental’ language version

3. Dictionary Initializer

Before

The old way of writing a dictionary initializer is as follows:

C#
public class DictionaryInitializerBeforeCSharp6
{
    public Dictionary<string, string> _users = new Dictionary<string, string>()
    {
        {"users", "Venkat Baggu Blog" },
        {"Features", "Whats new in C# 6" }
    };
}

After

We can define dictionary initializer like an array using square brackets.

C#
public class DictionaryInitializerInCSharp6
{
    public Dictionary<string, string> _users { get; } = new Dictionary<string, string>()
    {
        ["users"]  = "Venkat Baggu Blog",
        ["Features"] =  "Whats new in C# 6" 
    };
}

4. Declaration Expressions

Before

C#
public class DeclarationExpressionsBeforeCShapr6()
{
    public static int CheckUserExist(string userId)
    {
        //Example 1
        int id;
        if (!int.TryParse(userId, out id))
        {
            return id;
        }
        return id;
    }

    public static string GetUserRole(long userId)
    {
        ////Example 2
        var user = _userRepository.Users.FindById(x => x.UserID == userId);
        if (user!=null)
        {
            // work with address ...

            return user.City;
        }
    }
}

After

In C# 6, you can declare an local variable in the middle of the expression. With declaration expressions, we can also declare variables inside if statements and various loop statements.

C#
public class DeclarationExpressionsInCShapr6()
{
    public static int CheckUserExist(string userId)
    {
        if (!int.TryParse(userId, out var id))
        {
            return id;
        }
        return 0;
    }

    public static string GetUserRole(long userId)
    {
        ////Example 2
        if ((var user = _userRepository.Users.FindById(x => x.UserID == userId) != null)
        {
            // work with address ...

            return user.City;
        }
    }
}

5. Using Statics

Before

To you static members, you don’t need an instance of object to invoke a method. You use syntax as follows:

C#
TypeName.MethodName
C#
public class StaticUsingBeforeCSharp6
{
    public void TestMethod()
    {
        Console.WriteLine("Static Using Before C# 6");
    }
}

After

In C# 6, you have the ability to use the Static Members without using the type name. You can import the static classes in the namespaces.

If you look at the below example, we moved the Static Console class to the namespace:

C#
using System.Console;
namespace newfeatureincsharp6
{
    public class StaticUsingInCSharp6
    {
        public void TestMethod()
        {
            WriteLine("Static Using Before C# 6");
        }
    }
}

6. await Inside catch Block

Before C# 6, await keyword is not available inside the catch and finally blocks. In C# 6, we can finally use the await keyword inside catch and finally blocks.

C#
try 
{	        
	//Do something
}
catch (Exception)
{
	await Logger.Error("exception logging")
}

7. Exception Filters

Exception filters allow you a feature to check an if condition before the catch block executes.

Consider an example that an exception occurred now we want to check if the InnerException null, then it will execute catch block.

C#
//Example 1
try
{
    //Some code
}
catch (Exception ex) if (ex.InnerException == null)
{
    //Do work

}

//Before C# 6 we write the above code as follows

//Example 1
try
{
    //Some code
}
catch (Exception ex) 
{
    if(ex.InnerException != null)
    {
        //Do work;
    }
}

8. Conditional Access Operator to Check NULL Values?

Consider an example that we want to retrieve a UserRanking based on the UserID only if UserID is not null.

Before

C#
var userRank = "No Rank";
if(UserID != null)
{
    userRank = Rank;
}

//or

var userRank = UserID != null ? Rank : "No Rank" 

After

C#
var userRank = UserID?.Rank ?? "No Rank";

The post New features in C# 6.0 appeared first on Venkat Baggu Blog.

This article was originally posted at http://venkatbaggu.com/new-features-in-c-6-0

License

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


Written By
Software Developer (Senior) eBiz Solutions http://venkatbaggu.com/
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Praisegood summary Pin
Southmountain11-Nov-22 13:54
Southmountain11-Nov-22 13:54 
QuestionException filter Pin
loucassagnou30-Aug-16 3:56
loucassagnou30-Aug-16 3:56 
Question[My vote of 1] no read, just write?? Pin
Thornik10-Feb-15 19:58
Thornik10-Feb-15 19:58 
Question[My vote of 2] Updates needed Pin
Jeremy Todd10-Feb-15 10:13
Jeremy Todd10-Feb-15 10:13 
AnswerRe: [My vote of 2] Updates needed Pin
madan53510-Feb-15 16:39
madan53510-Feb-15 16:39 
GeneralMy vote of 5 Pin
Volynsky Alex9-Feb-15 13:27
professionalVolynsky Alex9-Feb-15 13:27 

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.