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:
// C# program to create singleton ValueTuple // using the value tuple constructor using System;
class GFG {
// Main method
static public void Main()
{
// Creating a value tuple with one element
// Using ValueTuple<T1>(T1) constructor
ValueTuple< string > MyTpl = new ValueTuple< string >( "GeeksforGeeks" );
Console.WriteLine( "Component is: " + MyTpl.Item1);
}
} |
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:
// C# program to create a singleton value // tuple using Create<T1>(T1) method using System;
public class GFG {
// Main method
static public void Main()
{
// Creating a value tuple with one element
// Using Create<T1>(T1) method
var MyTple = ValueTuple.Create( "Geeks123" );
Console.WriteLine( "Component: " + MyTple.Item1);
}
} |
Component: Geeks123
Reference:
- https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-1.-ctor?view=netframework-4.8
- https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple.create?view=netframework-4.8#System_ValueTuple_Create__1___0_