Navigation

Saturday 29 August 2015

New features in C# .NET 6.0

Below are the new features expected to come in upcoming .NET release C# 6.0
  1. Auto Property Initializer 
  2. Primary Constructor and its Body
  3. Import Static members with the help of "using"
  4. Exception Filters
  5. Dictionary Initializer
  6. Conditional access operator to check null values.
Let's see brief description about each below.

1. Auto Property Initializer 

we can initialize property values directly without declaring private fields or within the constructor. See below example

Before C# 6.0

public class Employee
{
    public Employee()
    {
        Salary = 10000;
    }

    public int Salary { get; set; }

    private string _company = "Your Company";

    public string Company
    {
        get { return _company; }
        set { _company = value; }
    }
}

We can write above code using C# 6.0 as below.

public class Employee
{
    public int Salary { get; set; } = 1000;

    public string Company { get; set; } = "Your Company";
   
}


So no more required constructor or private fields to initialize auto properties.

2. Primary Constructor and its Body

In C# 6.0, we can define constructor side by class name itself. Below is the example

Before c# 6.0 

public class Employee
{
    public Employee()
    {
        Salary = 10000;
        Company = "Your Company";
    }

    public int Salary { get; set; }

    public string Company { get; set; }
}

In C# 6.0 


public class Employee(int salary, string company)
{
    public int Salary { get; set; } = salary;

    public string Company { get; set; } = company;
}


3. Import Static members with the help of "using"

In C# 6.0 we no need to access static members with the help of class name, instead we can import static class with help of "using" as we do for namespaces so that we can directly access static variables.

Before C# 6.0

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your username");
        }
    }
}

In C# 6.0

using System.Console;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Enter your username");
        }
    }
}



No comments:

Post a Comment