I have written a piece of code to check for Object Equality. I took refrence from one of the question in stack overflow itself. Now this code is giving true even if we have two different objects. Can someone explain why?
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 (obj == 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(); } } } and in my UtilityClass
static class utility { public static int SafeGetHashCode<T>(this T value) where T : class { return value == null ? 0 : value.GetHashCode(); } } After no success,i tried below code which also return true. What blunder am I doing here?Please help
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(); } }
Test test = obj as Test; if (obj == null)should have beenTest test = obj as Test; if (test == null)