Introduction
Tuple is a data structure that allows us to store a collection of elements of different data types. Tuples are immutable which means their contents cannot be changed once they are created. In this blog, we will explore tuples in depth, covering their creation, usage, and best practices.
Creating a Tuple
Tuples can be created in C# in two primary ways:
- Using constructors
- Using ‘Tuple.Create’ method
- Tuple creation using constructor
we can create tuple using the ‘System.Tuple‘ class which provides constructors for creating tuples.
For Example:
Tuple<string, double, string> person = new Tuple<string, double, string>("John",24,"India");
In this example, Tuple<string, double, string> specifies the datatypes of the element in the tuple. That is, first element is of data type string, second element is of type double and third element is of string datatype. new Tuple(“John” 24,”India”) is initializing values using constructor.
2. Tuple creation using `Tuple.Create1` method
C# provides a convenient way to create tuples using the Tuple.Create
method, which infers the data types from the provided values.
For example:
var person = Tuple.Create("John", 30, 3.14);
Accessing Elements in a Tuple
Once you have created a tuple, you can access its elements using the Item1
, Item2
, and so on properties.
For example:
Eg :
var person = Tuple.Create("John",24,"India");
Console.WriteLine("Name : "+person.Item1); //Prints Name : John
Console.WriteLine("Age : "+person.Item2.ToString()); //Prints Age : 24
Console.lWriteLine("Country : "+person.Item3); //Prints Country : India
Named Tuples
Starting from C# 7.0, you can create named tuples for improved code readability.
(string Name, double Age, string Grade) person = ("John", 30, "A");
With named tuples, you can access elements by their names.Named tuples make your code more self-explanatory and reduce the risk of errors when working with tuples containing multiple elements.
string name = person.Name;
double age = person.Age;
string grade = person.Grade;
Nested Tuples
C# allows us to create a tuple of upto seven elements. When we need to create tuple consisting of more than 7 elements, we can use nested tuples. We can create and include the nested tuple anywhere in the sequence.
Eg:
var tuple = Tuple.Create(100, 200, 300, 400, 500, 600, Tuple.Create(700, 800, 900),1000 );
Accessing elements of nested tuple:
Console.WriteLine(tuple.Item7.Item1); //Prints 700
Console.WriteLine(tuple.Item7.Item2); //Prints 800
Console.WriteLine(tuple.Item7.Item3); //Prints 900
Console.WriteLine(tuple.Item7.Item4); //Prints 1000
Conclusion
And now, we discussed about how to create and work with tuple.
No Comment! Be the first one.