How to easily initialize a list of Tuples in C#?


Tuple can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it. The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types.

Tuple<int, string, string> person =
new Tuple <int, string, string>(1, "Test", "Test1");

A tuple can only include a maximum of eight elements. It gives a compiler error when you try to include more than eight elements.

Tuples of List

var tupleList = new List<(int, string)>
{
   (1, "cow1"),
   (5, "chickens1"),
   (1, "airplane1")
};

Tuples of Array

var tupleArray = new(int, string)[]
{
   (1, "cow1"),
   (5, "chickens1"),
   (1, "airplane1")
};

Nested Tuples

var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13));
Tuple as a Method Parameter
static void DisplayTuple(Tuple<int,string,string> person)
{
}

Tuple as a Return Type

static Tuple<int, string, string> GetTest()
{
   return Tuple.Create(1, "Test1", "Test2");
}

Updated on: 07-Nov-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements