What is a C analog of C stdpair?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
C++ provides a versatile and convenient data structure called std::pair that allows programmers to store and manipulate two values of potentially different types. This is particularly useful in tasks such as implementing associative data structures or returning multiple values from functions without creating custom data classes or structs. In the C# programming world, there is no direct equivalent named std::pair, but the functionality can be similarly achieved using C#'s Tuple<T1, T2> or by creating custom types. This article explores these alternatives, providing technical details and examples.
Understanding std::pair in C++
Before diving into C# alternatives, it’s important to understand the C++ std::pair. The std::pair template in the C++ Standard Library encapsulates a pair of values:
In this code, the std::pair holds an int and a std::string, accessible via first and second.
C# Equivalent: Tuple<T1, T2>
In C#, the most direct analog to a C++ std::pair is the Tuple<T1, T2> class. The Tuple class can encapsulate two items of potentially differing types:
Custom Structs in C#
For more control over the behavior and semantics of the pair, custom struct types can be created:
This approach provides flexibility and clarity by enabling custom names and potential mutability.
Conclusion
While C# does not provide a std::pair analogous class, its Tuple<T1, T2>, along with optional custom structs, addresses the same range of use cases. Each method has its advantages, from simplicity and readability with Tuple<T1, T2> to the tailored design and performance of custom structures. Depending on the specific needs of a project, one can choose between these options to best mimic the std::pair capabilities available in C++.
Related reading
- What is a dependency property?
- What is a good choice of database for a small .NET application?
- What is a method group in C?
- What is a .NET application domain?
- What is a first chance exception?
- What is a good open source B-tree implementation in C?
- What is a NullReferenceException, and how do I fix it?
- What is a Portable Class Library?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.