2017年8月15日 星期二

[C#] 7.0 New feature - Tuples

 C#7.0    Tuples  


Introduction


One of the new features in C# 7.0, tuple types and literals, which can be used to return more than one value from a method.

Notice that the System.ValueTuple structs is implemented in assembly: System.ValueTuple


You can install it thru NuGet.


Environment

Visual Studio 2017



Samples


Method with Tuple return type

private static (Employee, string) getEmployee()
{
            var emp = new Employee() {
                Id = "1234",
                Name = "JB Lin",
                Age = 36
            };
            return (emp, "Full-stack developer, father");
}

OR-

private static Tuple<Employee, string> getEmployee()
{
      var emp = new Employee() {
                Id = "1234",
                Name = "JB Lin",
                Age = 36
      };
return new Tuple<Employee, string>(emp, "Full-stack developer, father");
}





Receive a tuple

There are several ways to call the method and receive the Tuple.

1.

Employee jb = null;
string description = string.Empty;
 (jb, description) = getEmployee();

2.

var (jb, description) = getEmployee();


3.

(Employee jb, string description) = getEmployee();


4.

var tuple = getEmployee();
var jb = tuple.Item1;
var description = tuple.Item2;




Reference


沒有留言:

張貼留言