C# Tuples Guide: Create & Use

In C#, a tuple is a data structure used to store multiple values of different types. Tuples can be used to return multiple values or pass multiple values as parameters to a method.

There are multiple ways to create a tuple. Here are two commonly used methods:

  1. Use tuple literal syntax:
var tuple = (1, "hello", true);

This will create a tuple containing three values: the integer 1, the string “hello”, and the boolean true.

  1. Constructing tuples by using the tuple constructor.
var tuple = new Tuple<int, string, bool>(1, "hello", true);

This will create a tuple identical to the example above.

After creation, you can access each element of the tuple using the following methods:

  1. Add punctuation with the name or index of the element.
var firstElement = tuple.Item1; // 访问第一个元素,值为1
var secondElement = tuple.Item2; // 访问第二个元素,值为"hello"
var thirdElement = tuple.Item3; // 访问第三个元素,值为true
  1. Pattern matching syntax:
(int number, string text, bool flag) = tuple; // 将元组的元素分别赋值给对应的变量

In this instance, the variable number will be assigned the value of 1, text will be assigned the value of “hello,” and flag will be assigned the value of true.

It is important to note that the elements of a tuple can be of different types, such as integers, strings, boolean values, etc. Using tuples can make it more convenient to return multiple values or pass multiple values as parameters to a method.

bannerAds