This post will discuss how to use Pair in C#.

1. Using C# 7.0 Tuples

A Pair is a container to store the values of two objects. The C# doesn’t provide any built-in implementation of the Pair class, but starting from .NET 4.0, you can use tuples to implement a pair-like structure:

Download  Run Code

 
C# 7.0 tuple lets you create instances of tuples, with or without having to explicitly specify the types of its components. For example, the following example assigns a tuple to individually declared and implicitly typed variables.

Download  Run Code

 
You can even assign a named item tuple to a single implicitly typed variable and then access the tuple items using their attribute.

Download  Run Code

2. Custom implementation

If you don’t want to use tuples, you can implement our own Pair class in C#. Here’s a simple custom implementation of the Pair class, where its First and Second fields can store any data type.

Download  Run Code

That’s all about using Pair in C#.