SoFunction
Updated on 2025-03-06

Discover the new features of C# 6.0

New features in C# 6.0

We can discuss these new features one by one, and first we need to list a list of these features in C# 6.0

Automatic Property Initializer

Primary Constructor

Dictionary Initializer

Declaration Expression

Using Static Using

await in catch block

Exception Filter

Conditional access operator for checking NULL values

1. Automatic property initialzier Auto Property initialzier

The previous way

The only way to initialize an automatic property Auto Property is to implement a clear constructor and set the property values ​​in it.

public class AutoPropertyBeforeCsharp6
{
  private string _postTitle = ;
  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;
    }
  }
}

The way after this feature is

Properties with initial values ​​that are automatically implemented in C# 6 can be initialized without writing a constructor. We can simplify the above example with the following code:

public class AutoPropertyInCsharp6
{
  public long PostID { get; } = 1;
 
  public string PostName { get; } = "Post 1";
 
  public string PostTitle { get; protected set; } = ;
}

2. Main constructor

We use the constructor to initialize the values ​​inside. (Accept parameter values ​​and assign these parameter values ​​to entity properties).

The previous way

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; }
}

The way after this feature is

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, the main constructor provides us with a brief syntax to define the constructor using parameters. Each class can have only one main constructor.

If you observe the example above, you will find that we moved the parameter initialization next to the class name.

You may get the following error "Feature 'primary constructor' is only available in 'experimental' language version." To solve this problem, we need to edit the file to avoid this error. All you have to do is add additional settings after WarningTag

<LangVersion>experimental</LangVersion>

The ‘main constructor’ is only available in language versions of the ‘experimental’ nature

3. Dictionary Initializer

The previous way

The old way to write a 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" }
  };
}

The way after this feature is

We can define a dictionary initializer like using square brackets in an array

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

4. Declare expressions

The previous way

public class DeclarationExpressionsBeforeCShapr6()
{
  public static int CheckUserExist(string userId)
  {
    //Example 1
    int id;
    if (!(userId, out id))
    {
      return id;
    }
    return id;
  }
 
  public static string GetUserRole(long userId)
  {
    ////Example 2
    var user = _userRepository.(x =>  == userId);
    if (user!=null)
    {
      // work with address ...
 
      return ;
    }
  }
}

The way after this feature is

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

public class DeclarationExpressionsInCShapr6()
{
  public static int CheckUserExist(string userId)
  {
    if (!(userId, out var id))
    {
      return id;
    }
    return 0;
  }
 
  public static string GetUserRole(long userId)
  {
    ////Example 2
    if ((var user = _userRepository.(x =>  == userId) != null)
    {
      // work with address ...
 
      return ;
    }
  }
}

5. Static Using

The previous way

For your static members, there is no need to make an object instance in order to call a method. You will use the following syntax



public class StaticUsingBeforeCSharp6
{
  public void TestMethod()
  {
    ("Static Using Before C# 6");
  }
}

The way afterwards

In C# 6, you can use static members without class names. You can introduce static classes in the namespace.

If you look at the following example, you will see that we move the static Console class into the namespace

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

6. Await in the catch block

Before C# 6, the keyword await cannot be used in catch and finally blocks. In C# 6, we can finally use await in these two places.

try 
{     
 //Do something
}
catch (Exception)
{
 await ("exception logging")
}

7. Exception filter

The exception filter allows you to make an if condition judgment before the catch block is executed.

Look at this example where an exception occurred. Now we want to first determine whether the Exception is null, and then execute the catch block

//Example 1try
{
  //Some code
}
catch (Exception ex) if ( == null)
{
  //Do work
 
}
 
//Before C# 6 we write the above code as follows
 
//Example 1try
{
  //Some code
}
catch (Exception ex) 
{
  if( != null)
  {
    //Do work;
  }
}

8. Conditional access operator used to check NULL values?.

Looking at this example, we extract a UserRanking based on the condition that the UserID is not null.

The previous way

var userRank = "No Rank";
if(UserID != null)
{
  userRank = Rank;
}
 
//or
 
var userRank = UserID != null ? Rank : "No Rank"

With this feature

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

The above is the entire content of this article, I hope you like it.