Open In App

How to create 1-ValueTuple in C#?

Improve
Improve
Like Article
Like
Save
Share
Report

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:




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


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:




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


Output:

Component: Geeks123

Reference:



Last Updated : 23 Jul, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads