Open In App

C# ValueTuple <T1> Struct

Last Updated : 18 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

ValueTuple<T1> struct in C# is part of the System namespace and it is used to create a tuple that stores a single component. It offers a more lightweight, value-type tuple compared to the older Tuple class and provides better performance and memory management. The ValueTuple<T1> struct is a value type and mutable means the value of its single element can be modified.

Constructor

The constructor for ValueTuple<T1> initializes the tuple with a single value:

// Initializes a new ValueTuple<T1> instance

ValueTuple<T1>(T1)

Field

Item1: The public field of ValueTuple<T1>, which holds the single element. It is not a property, it is a field that can be accessed directly.

Example: Demonstration of access to the ValueTuple<T1> element in C#.

C#
// Accessing ValueTuple<T1> element
using System;

class Geeks
{
	static public void Main()
	{
		// Creating a value tuple 
		// Using Create method 
		var vt = ValueTuple.Create(357);

		// Display the element of the given value tuple 
		Console.WriteLine("Item 1: {0}", vt.Item1);
	}
}

Output
Item 1: 357

Explanation: In the above example, it creates a ValueTuple with a single element 357 and prints the value of Item1 to the console.

Methods

Method

Description

CompareTo(ValueTuple)

It compares the current ValueTuple<T1> instance to a specified ValueTuple<T1> instance.

Equals(Object)

It returns a value that indicates whether the current ValueTuple<T1> instance equals a specified object.

Equals(ValueTuple<T1>)

It returns a value that indicates whether the current ValueTuple<T1> instance equals a specified ValueTuple<T1> instance.

GetHashCode()

It calculates the hash code for the current ValueTuple<T1> instance.

ToString()

It returns a string that represents the value of this ValueTuple<T1> instance.

Example:

C#
// Check if value tuples are Equal
using System;

class Geeks
{
	static public void Main()
	{
		// Creating 1-ValueTuple 
		// Using Create method 
		var T1 = ValueTuple.Create(346);
		var T2 = ValueTuple.Create(346);

		// Check if both the value tuples 
		// are equal or not 
		if (T1.Equals(T2))
			Console.WriteLine("Code is correct...!!");
		else
			Console.WriteLine("Incorrect Code...!!");
	}
}

Output
Code is correct...!!

Key Features:

  • Single Element: A ValueTuple<T1> contains only one element, referred to as Item1.
  • Mutable: The value of Item1 can be changed after the tuple is created.
  • Type-Safe: The type of Item1 is specified when the tuple is created, ensuring type safety.
  • Implements Interfaces: ValueTuple<T1> implements several interfaces such as:
    • IStructuralComparable
    • IStructuralEquatable
    • IComparable<ValueTuple<T1>>
    • IEquatable<ValueTuple<T1>>
    • ITuple: This makes it useful in various comparison and equality scenarios.

Next Article
Article Tags :

Similar Reads