How to create 1-ValueTuple in C#?
In C#, a Singleton or 1-ValueTuple is a value type tuple which holds only one Component. You can create a singleton value tuple using two different ways:
- Using ValueTuple <T1>(T1) Constructor
- Using Create <T1>(T1) Method
Using ValueTuple <T1>(T1) Constructor
You can create a singleton value tuple using ValueTuple <T1>(T1) constructor. This constructor initializes a new instance of ValueTuple<T1> struct. But when you create a value tuple using this constructor, then you have to specify the type of the element stored in the value tuple.
Syntax:
public ValueTuple (T1 item1);
Here, item1 is the only component of the value tuple.
Example:
using System;
class GFG {
static public void Main()
{
ValueTuple< string > MyTpl = new ValueTuple< string >( "GeeksforGeeks" );
Console.WriteLine( "Component is: " + MyTpl.Item1);
}
}
|
Output:
Component is: GeeksforGeeks
Using Create <T1>(T1) Method
You can also create a singleton value tuple with the help of Create <T1>(T1) method. When you use this method, then there is no need to specify the type of the elements stored in the value tuple.
Syntax:
public static ValueTuple<T1> Create<T1> (T1 item1);
Here, item1 is the value of the value tuple component and T1 is the type of the element stored in the value tuple.
Return Type: This method returns a value tuple with one element.
Example:
using System;
public class GFG {
static public void Main()
{
var MyTple = ValueTuple.Create( "Geeks123" );
Console.WriteLine( "Component: " + MyTple.Item1);
}
}
|
Output:
Component: Geeks123
Reference:
Last Updated :
23 Jul, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...