![]() |
VOOZH | about |
ValueTuple Struct in C# is a structure that provides static methods that are used in creating value tuples. It is defined under the System namespace and was introduced in .NET Framework 4.7. This struct enables runtime implementation tuples in C#. The ValueTuple structure represents a tuple that can contain from 0 to 8 elements.
ValueTuple is different from the Tuple class in the following terms:
Note: ValueTuple implements IStructuralComparable, IStructuralEquatable, IComparable, IComparable<ValueTuple>, IEquatable<ValueTuple>, and ITuple interfaces.
We can declare a ValueTuple using different ways some of which are shown below:
// Using parenthesis
var person = (1, "Geek", "C#", 3.0);// Using the Create Method:
var person = ValueTuple.Create (1, "Geek", "C#", 3.0);// Using Constructor
var T1 = new ValueTuple<int, string, double>(2, "Coder", 2.71);
Example: Different Ways to Create ValueTuples
Output:
Note: Creating tuple Using parenthesis() was introduced in C# 7.0. We have version earlier than C# 7.0, this syntax will not be recognized and will result in a compilation error.
Method | Description |
|---|---|
Create() | Creates a new value tuple with zero components. |
CompareTo(ValueTuple) | Compares the current ValueTuple instance to a specified ValueTuple instance. |
ToString() | Returns the string representation of this ValueTuple instance. |
Returns the hash code for the current ValueTuple instance. | |
Returns a value indicating whether the current ValueTuple instance equals a specified object. | |
Equals(ValueTuple) | Determines whether two ValueTuple instances are equal. This method always returns true. |
Create<T1>(T1) | Creates a new value tuple with 1 component (a singleton). |
Create<T1, T2>(T1, T2) | Creates a new value tuple with 2 components (a pair). |
Create<T1, T2, T3>(T1, T2, T3) | Creates a new value tuple with 3 components (a triple). |
Create<T1, T2, T3, T4>(T1, T2, T3, T4) | Creates a new value tuple with 4 components (a quadruple). |
Create<T1, T2, T3, T4, T5>(T1, T2, T3, T4, T5) | Creates a new value tuple with 5 components (a quintuple). |
Create<T1, T2, T3, T4, T5, T6>(T1, T2, T3, T4, T5, T6) | Creates a new value tuple with 6 components (a sextuple). |
Create<T1, T2, T3, T4, T5, T6, T7>(T1, T2, T3, T4, T5, T6, T7) | Creates a new value tuple with 7 components (a septuple). |
Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1, T2, T3, T4, T5, T6, T7, T8) | Creates a new value tuple with 8 components (an octuple). |
Example: Demonstration of Using Different methods on ValueTuple in C#.
HashCode of a value tuple with zero elements: 0 CompareTo Method Result: -1