Skip to main content

C# 6.0 New feature





New features in C# 6.0

We can discuss about each of the new feature but first 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.
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 with out having to write the constructor. We can simplify the above example to the following
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

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

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 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
<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 writing an dictionary initializer is as follows
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
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

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 middle of the expression. With declaration expressions we can also declare variables inside if statements and various loop statements
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
TypeName.MethodName
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 with out 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
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 block. In C# 6 we can finally use the await keyword inside catch and finally blocks.
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 excutes.
Consider an example that an exception occurred now we want to check if the InnerException null then it will executes catch block
//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 an UserRanking based on the UserID only if UserID is not null.

Before

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

//or

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

Comments

Popular posts from this blog

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome

Code First Getting Started

In this tutorial let us create a simple application to demonstrate the use of entity framework using code first. We are using Visual Studio 2015 and entity framework 6.1.3. You can download Visual Studio community Edition . You should have the basic knowledge of .Net framework, C# and MS SQL Server. In this tutorial, we will create a simple application with a user class.  Our user class will have basic information like name and email address of the user. Create the Project Open Visual Studio. File ->New -> Project Select C# -> Select Console Application Name the application as “EFGettingStarted” Click on OK Install Entity Framework The next step is to install the Entity framework. This can be installed via nuget package console. Click on Tools->Nuget Package manager -> Package Manager Console and type the following command C# 1 2 3   install - package entityframework   This will install the late

First, FirstOrDefault, Single, SingleOrDefault In C#

For people who are new to LINQ, it is difficult to understand the difference between First, FirstOrDefault, Single, SingleOrDefault. In this blog, I will explain what to use and when.     I will take a simple example to make you understand practically how these methods work.   Consider a class Employee with properties as Id, Name, and Department. class  Employee {    public   int  Id {  get ;  set ; }    public   string  Name {  get ;  set ; }    public   string  Department{  get ;  set ; } } I have a list of Employees: List<Employee> employeeList =  new  List<Employee>(){    new  Employee() { Id = 1, Name =  "Sunny" , Department =  "Technical"  },    new  Employee() { Id=2, Name= "Pinki" , Department = "HR" },    new  Employee() { Id=3, Name= "Tensy" , Department = "Finance" },    new  Employee() { Id=4, Name= "Bobby" , Department = "Technical" },    new