In the previous post I wrote about out variables and pattern matching in C# 7.0. Today I will focus on another features which are Tuples.
Tuple is not new thing, we have it already in C#, but this time the newest version of C# adds tuple types and tuple literals. With C# 7.0 we can implement method looks like this
1 2 3 4 |
(string, string, string) GetValues() // tuple return type { return ("TestVal1", "TestVal2", "TestVal3"); // tuple literal } |
GetValues method returns tuple object that contains three fields. Let’s take a look at example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class Tuples { public void Run() { var tupleType1 = GetValues1(); Console.WriteLine($"{tupleType1.Item1}, {tupleType1.Item2}, {tupleType1.Item3}"); var tupleType2 = GetValues2(); Console.WriteLine($"{tupleType2.Val1}, {tupleType2.Val2}, {tupleType2.Val3}"); //it works as well Console.WriteLine($"{tupleType2.Item1}, {tupleType2.Item2}, {tupleType2.Item3}"); } (string, string, string) GetValues1() // tuple return type { return ("TestVal1", "TestVal2", "TestVal3"); // tuple literal } (string Val1, string Val2, string Val3) GetValues2() // tuple return type { return (Val1: "TestVal1", Val2: "TestVal2", Val3: "TestVal3"); // tuple literal } } |
As you can see in GetValues1 method I didn’t specified names for fields, so to get value we need to use default names like Item1, Item2, …, ItemN. We can change it and add our own names for fields. Take a look at the second example of method – GetValues2. In this method I specified field names: Val1, Val2, Val3. When we use this tuple return type we have a hint from IntelliSense with our field names. Item1, Item2, Item3 fields aren’t visible, but we can use it as well and it works.
In addition we can assign tuple return type to new local variables, it’s called deconstructing declaration.
1 2 3 4 5 6 7 |
(string val1, var val2, var val3) = GetValues2(); Console.WriteLine($"{val1}, {val2}, {val3}"); //or var (a, b, c) = GetValues1(); Console.WriteLine($"{a}, {b}, {c}"); |
If we want to assign result to existing variables we can do it as well.
1 2 3 |
string x, y, z; (x, y, z) = GetValues1(); Console.WriteLine($"{x}, {y}, {z}"); |
It’s also good to mention that if you don’t use the latest .NET Framework, but you want to use the newest Tuples, you can do it. Just install the right package from NuGet Packages – System.ValueTuple.