In Beta

Complete List of Advanced C# 7 Features Web Developer Should Know


C# 7 recently added features focuses on simplification of code, performance, and consumption of data. These features are fully functional in visual studio 2017 but some features can also be used in Visual Studio “15” Preview 4.

So without further ado, let's take a look at the new C# 7 features: 

1. Out Variables 

Out variables are used for returning multiple values from a function. Unlike the return statement which is capable of returning only one value from a function. Arguments are passed by reference throughout the keyword. Out variables were available prior to C# 7 but had following difference. Before C# 7, the Out variables were declared in a separate statement. Whenever there was a requirement of calling a method without parameters, then these variables were used as an out parameter in the method.

Example :

 

 class Program
 {
    static void Main(string[] args)  
    {   
        //Out variable declaration in separate statement
        int studentId;
        string studentName;
        GetDetails(out studentId, out studentName);
        Console.WriteLine("studentId: {0}, studentName: {1}",studentId,studentName);
        Console.ReadKey();
    }
    public static void GetDetails(out int studentId, out string studentName)  
    {  
        studentId = 10;  
        studentName = "Kapil";
        Console.WriteLine("studentId: {0}, studentName: {1}", studentId, studentName);  
    }
}

 Note :

  • var keyword cannot be used to declare out keyword
  • out keyword cannot be used with the async method

 In C# 7, the usage of out variable is the same as it was before. The only difference is in the declaration. Out variables can now be declared at the point where it is passed as an out argument.

Example:

using System;
namespace CSharp7Features
{
    class Program
    {
        static void Main(string[] args)
        {
            GetDetails(out int studentId, out string studentName);  //Out variable declared where it is passed as an argument
            Console.WriteLine($"studentId: { studentId }, studentName: { studentName }");
            Console.ReadKey();
        }
        public static void GetDetails(out int studentId, out string studentName)
        {
            studentId = 10;
            studentName = "Kapil";
            Console.WriteLine($"studentId: { studentId }, studentName: { studentName }");
        }
    }
}

Note :

  • var keyword can be used to declare out keyword

 Following Statement

GetDetails(out int studentId, out string studentName);

 Can be replaced by

GetDetails(out var studentId, out var studentName);

Checkout the full code here>> Advanced C# 7 Features Web Developer Should Know