Implementing Multi-Value Dictionaries in C# with a Generic Pair Class

Dec 07, 2025 · Programming · 10 views · 7.8

Keywords: C# | Multi-Value Dictionary | Pair | Generic Programming

Abstract: This article explains how to implement a multi-value dictionary in C# using a generic Pair class. It details the implementation of the Pair class, including equality comparison and hash code computation, and provides usage examples along with comparisons to alternative methods. Through step-by-step analysis of core concepts, it maintains a high level of technical rigor, ensuring a comprehensive and detailed technical paper.

Introduction

In C#, developers often encounter situations where they need to store multiple values under a single key in a dictionary. The standard Dictionary<TKey, TValue> supports only one value per key. This article addresses how to create a multi-value dictionary, such as Dictionary<int, object, double>, by implementing a generic Pair<TFirst, TSecond> class as the primary solution, with step-by-step explanations to illustrate key points accessibly.

Implementing the Pair Class

The core solution involves creating a sealed class that holds two values. Based on the best answer, here is a detailed implementation:

using System;
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond>
    : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first;
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second)
    {
        this.first = first;
        this.second = second;
    }

    public TFirst First
    {
        get { return first; }
    }

    public TSecond Second
    {
        get { return second; }
    }

    public bool Equals(Pair<TFirst, TSecond> other)
    {
        if (other == null)
        {
            return false;
        }
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
               EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

    public override bool Equals(object o)
    {
        return Equals(o as Pair<TFirst, TSecond>);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
               EqualityComparer<TSecond>.Default.GetHashCode(second);
    }
}

This class implements IEquatable<T> for efficient equality checks and overrides Equals and GetHashCode to ensure proper behavior in collections like dictionaries. This guarantees consistency, making dictionary operations more reliable.

Using the Pair Class in a Dictionary

With the Pair class, you can create a dictionary that stores multiple values per key. For example:

var dict = new Dictionary<int, Pair<object, double>>();
dict.Add(1, new Pair<object, double>(new Object(), 2.22));

This approach allows associating an object and a double with a single integer key, essentially implementing a multi-value dictionary. By comparing with other methods, such as structs or Tuple, the Pair class shows advantages in performance and strong typing support.

Supplementary Methods

Based on other answers, alternative approaches include using a struct to group values:

public struct MyValue
{
    public object Value1;
    public double Value2;
}

var dict = new Dictionary<int, MyValue>();

Additionally, a custom dictionary class can simplify adding values:

public class MyDictionary : Dictionary<int, MyValue>
{
    public void Add(int key, object value1, double value2)
    {
        MyValue val;
        val.Value1 = value1;
        val.Value2 = value2;
        this.Add(key, val);
    }
}

Another option is to use Tuple<T1, T2>, but note that Tuples are available from .NET 4.0 onwards, which may limit compatibility with older versions.

Conclusion

The Pair<TFirst, TSecond> class provides a robust solution for implementing multi-value dictionaries in C#. By ensuring correct equality and hash code implementations, it integrates seamlessly with standard collections. Balancing strong typing and performance, it stands as an excellent choice for most scenarios. This article offers a complete implementation roadmap through example-based analysis, facilitating in-depth learning and application.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.