How to use Pair in C#
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; public class Example { public static void Main() { Tuple<string, int> pair = new Tuple<string, int>("David", 25); Console.WriteLine(pair); // (David, 25) } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; public class Example { public static void Main() { (var Name, var Age) = ("David", 25); Console.WriteLine($"({Name}, {Age})"); // (David, 25) } } |
You can even assign a named item tuple to a single implicitly typed variable and then access the tuple items using their attribute.
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; public class Example { public static void Main() { var pair = (Name: "David", Age: 25); Console.WriteLine($"({pair.Name}, {pair.Age})"); // (David, 25) } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; public class Pair<T, U> { public T First { get; set; } public U Second { get; set; } public Pair(T first, U second) { this.First = first; this.Second = second; } public override string ToString() { return $"({First}, {Second})"; } }; public class Example { public static void Main() { Pair<string, int> pair = new Pair<string, int>("David", 25); Console.WriteLine(pair); // (David, 25) } } |
That’s all about using Pair in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)