My
previous
blog compared objects in C#, but in this blog I will provide the code to compare using Hash code. Now hash code does not guarantee complete unique hash value so we will use slight modification.
See this Code
- using System;
- namespace ConsolePractice
- {
- public class Test
- {
- public int Value { get; set; }
- public string String1 { get; set; }
- public string String2 { get; set; }
-
-
-
- public override int GetHashCode()
- {
- int hash = 19;
- hash = hash * 31 + Value;
- hash = hash * 31 + String1.SafeGetHashCode();
- hash = hash * 31 + String2.SafeGetHashCode();
- return hash;
- }
- public override bool Equals(object obj)
- {
- Test test = obj as Test;
- if (test== null)
- {
- return false;
- }
- return Value == test.Value &&
- String1 == test.String1 &&
- String2 == test.String2;
- }
- }
-
- class Demo
- {
- static void Main()
- {
- Test p1 = new Test
- {
- Value = 10,
- String1 = "Test1",
- String2 = "Test2"
- };
- Test p2 = new Test
- {
- Value = 10,
- String1 = "Test1",
- String2 = "Test2"
- };
- bool areEqual = p1.Equals(p2);
-
- Console.WriteLine(areEqual.ToString());
- Console.ReadLine();
-
- }
- }
- }
You need to provide "SafeGetHashCode" as an extension method in another utility class.
- namespace ConsolePractice
- {
- static class utility
- {
- public static int SafeGetHashCode<T>(this T value) where T : class
- {
- return value == null ? 0 : value.GetHashCode();
- }
- }
- }
We checked the value equality of two objects using hash code. What about reference equality?
Reference quality can checked using object.Equals (or any other way you want).
Note
There are many other ways such as
IEqualityComparer<Thing>, check the code below:
Code
- using System;
-
- using System.Collections.Generic;
-
-
- class ThingEqualityComparer : IEqualityComparer<Thing>
- {
- public bool Equals(Thing x, Thing y)
- {
- if (x == null || y == null)
- return false;
-
- return (x.Id == y.Id && x.Name == y.Name);
- }
-
- public int GetHashCode(Thing obj)
- {
- return obj.GetHashCode();
- }
- }
-
-
- public class Thing
- {
- public int Id { get; set; }
- public string Name { get; set; }
-
- }
- class Demo
- {
- static void Main()
- {
- Thing p1 = new Thing
- {
- Id = 10,
- Name = "Test1",
-
- };
- Thing p2 = new Thing
- {
- Id = 10,
- Name = "Test1",
-
- };
-
- var comparer = new ThingEqualityComparer();
- Console.WriteLine(comparer.Equals(p1, p2));
-
-
- Console.ReadLine();
-
- }
- }
Disclaimer
I have written this blog by researching some concepts and code from various sources. Jon Skeet,Eric Lippert and many others inspire me to learn.