Last Updated : 11 Jul, 2025
In C#, a Dictionary<TKey, TValue> is a collection of key-value pairs. When we work with dictionaries, we may need to check if two dictionaries are equal. This means they contain the exact same keys and values.
In this article, we are going to learn how to check dictionary equality both by reference and by value in C#.
Syntax:
public virtual bool Equals (object obj);
This method checks whether two dictionary variables point to the same object in memory.
Example 1: Checking Reference Equality
C#
// C# program to check reference equality
// of two dictionaries
using System;
using System.Collections.Generic;
class Geeks {
public static void Main() {
// Creating a Dictionary
Dictionary<string, string> d1 = new Dictionary<string, string>();
d1.Add("Sweta", "Noida");
d1.Add("Amiya", "Bengaluru");
// d1 refers to the same instance as d2
Dictionary<string, string> d2 = d1;
// Checking reference equality
Console.WriteLine(d1.Equals(d2));
}
}
Example 2: Checking Reference Inequality
C#
// C# program to show Equals returns false
// for different instances with same content
using System;
using System.Collections.Generic;
class Geeks {
public static void Main() {
// Creating first dictionary
Dictionary<string, string> d1 = new Dictionary<string, string>();
d1.Add("Sweta", "Noida");
// Creating second dictionary with same content
Dictionary<string, string> d2 = new Dictionary<string, string>();
d2.Add("Sweta", "Noida");
// Content is same, references are different
Console.WriteLine(d1.Equals(d2));
}
}
C# Program to Check Dictionary Equality by Value
To compare if two dictionaries have the same key-value pairs, here, we will use LINQ methods like Except().
Example: Value-Based Dictionary Comparison
C#
// C# program to compare dictionary values using LINQ
using System;
using System.Collections.Generic;
using System.Linq;
class Geeks {
public static void Main() {
// Creating first dictionary
Dictionary<string, string> d1 = new Dictionary<string, string>() {
{"Sweta", "Noida"},
{"Amiya", "Bengaluru"}
};
// Creating second dictionary with same
// key-value pairs in different order
Dictionary<string, string> d2 = new Dictionary<string, string>() {
{"Amiya", "Bengaluru"},
{"Sweta", "Noida"}
};
// Comparing dictionaries by content
bool areEqual = d1.Count == d2.Count && !d1.Except(d2).Any();
Console.WriteLine("Are dictionaries equal by value? " + areEqual);
}
}
Are dictionaries equal by value? True
Important Points:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4