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:

  1. Using ValueTuple <T1>(T1) Constructor
  2. 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

Component: Geeks123

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.