Open In App

How to create 2-ValueTuple in C#?

Improve
Improve
Like Article
Like
Save
Share
Report

In C#, a pair or 2 value tuple is a value type tuple which holds two elements in it. You can create a pair of value tuple using two different ways:

  1. Using ValueTuple <T1, T2>(T1, T2) Constructor
  2. Using Create <T1, T2>(T1, T2) Method

Using ValueTuple <T1, T2>(T1, T2) Constructor

You can create a pair value tuple by using ValueTuple <T1, T2>(T1, T2) constructor. It initializes a new instance of the ValueTuple <T1, T2> 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, T2 item2);

Parameters:

  • item1: It is the value of the first value tuple component.
  • item2: It is the value of the second value tuple component.

Example:




// C# program to create a pair ValueTuple
// using value tuple constructor
using System;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Creating a value tuple with two elements
        // Using ValueTuple<T1, T2>(T1, T2) constructor
        ValueTuple<string, string> MyTpl = new ValueTuple<string
                                         string>("Geeks", "GFG");
  
        Console.WriteLine("Component 1: " + MyTpl.Item1);
        Console.WriteLine("Component 2: " + MyTpl.Item2);
    }
}


Output:

Component 1: Geeks
Component 2: GFG

Using Create <T1, T2>(T1, T2) Method

You can also create a pair value tuple with the help of Create <T1, T2>(T1, T2) 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, T2> Create<T1, T2> (T1 item1, T2 item2);

Type Parameters:

  • T1: It is the type of the value tuple’s first component.
  • T2: It is the type of the value tuple’s second component.

Parameters:

  • item1: It is the value of the value tuple’s first component.
  • item2: It is the value of the value tuple’s second component.

Returns: This method returns a value tuple with two elements.

Example:




// C# program to create a pair value tuple
// using Create<T1, T2>(T1, T2) method
using System;
  
public class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Creating a value tuple with two elements
        // Using Create<T1, T2>(T1, T2) method
        var MyTple = ValueTuple.Create("Geeks123", "gfg");
  
        Console.WriteLine("Component 1: " + MyTple.Item1);
        Console.WriteLine("Component 2: " + MyTple.Item2);
    }
}


Output:

Component 1: Geeks123
Component 2: gfg

Reference:



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