How to get First Element of the ValueTuple in C#?

In this article, we will discuss how to get the First Element of the ValueTuple in C#. But before going to its implementation, we must know about the tuple and valuetuple.

What is a Tuple?

A tuple denotes a data structure made up of multiple parts. A tuple is a data structure that provides the simplest method to describe a data collection with numerous values that may or may not be connected. It originated in .NET Framework 4.0. A tuple can include members ranging from 1 to 8. If we try to add more than eight items, the compiler will return an error. When we wish to construct a data structure that includes objects with their attributes, and we don't want to create a separate type for it, we often use tuples.

Features of Tuples:

There are several features of tuples. Some main features of the tuples are as follows:

  1. It enables us to combine numerous datasets into a single data collection.
  2. It enables us to produce, manipulate, and access datasets.
  3. It returns many values from a method without requiring the out argument.
  4. It can also save duplicate items.
  5. It allows us to send numerous values to a method using a single argument.

What is the Value Tuple?

The ValueTuple structure, introduced in C# 7.0, contains the value type Tuple. It is already included in the .NET Framework 4.7 and later versions. It allows us to save a data collection with various values that may or may not be connected. It is capable of storing components ranging from 0 to 8 and of various sorts. We may also store duplicate items in a value tuple.

The Item1 property is used to retrieve the first unidentified element of a given value tuple. It is applicable to all value tuples, including 1-ValueTuple, 2-ValueTuple, etc. Unlike Tuple, ValueTuples enables an easy method for creating and initializing ValueTuples.

Syntax:

It has the following syntax:

Here, T1 represents the field value of a ValueTuple<> structure. This ValueTuple<> can be a 1-, 2-, 3-, 4-, 5-, 6-, 7-, or 8-valued tuple.

Example:

Let us take an example to illustrate the valuetuple in C#.

Filename: ValueTuple.cs

Output:

The C# Topics: 
The Variables of the ValueTuple
Arrays
ArrayLists
Polymorphism
Identifiers
Nullable Types
Inheritance 
Parameters

Explanation:

The program defines numerous ValueTuples, each with a distinct amount of components.

  • var ValTupl1 = ValueTuple.Create("The Variables of the ValueTuple");: The Item1 property is used to retrieve the first member of each ValueTuple.
  • The ValueTuple creates many ValueTuples (ValTupl1, ValTupl2,..., ValTupl8). ValueTuple.Create method.
  • Each ValueTuple has a varied amount of string components that represent distinct C# subjects. The structure of ValueTuple creation and element access is consistently replicated for each tuple. In this example, Console.WriteLine(ValTupl1.Item1) outputs the first component in every ValueTuple.





Latest Courses