/ Published in: C#
![](/img/icon_sav.png?v3)
Why? So that your class can be used with collection classes.
// basic class
Every object has a GetHashCode() and Equals() method by default which it inherits from Object. Unfortunately these methods are useless as they stand because they say nothing specific about the class. As is, two objects of type MyStuff will only ever be equal if they are the same object (point to the same reference), making them of no use with collections.
// useful class
Add GetHashCode(), Equals() methods so that you can use the class with the Contains() method and other methods of IEnumerable collections.
I stole this from Jonathan McCracken: Test-Drive ASP.NET MCV
// basic class
Every object has a GetHashCode() and Equals() method by default which it inherits from Object. Unfortunately these methods are useless as they stand because they say nothing specific about the class. As is, two objects of type MyStuff will only ever be equal if they are the same object (point to the same reference), making them of no use with collections.
// useful class
Add GetHashCode(), Equals() methods so that you can use the class with the Contains() method and other methods of IEnumerable collections.
I stole this from Jonathan McCracken: Test-Drive ASP.NET MCV
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// basic class public class MyStuff { public int Id { get; set; } public string Name { get; set; } public int MyValue { get; set; } } // useful class public class MyStuff { public int Id { get; set; } public string Name { get; set; } public int MyValue { get; set; } public override int GetHashCode(){ return Id; } public override bool Equals(object obj){ if (ReferenceEquals(this, obj)) return true; var other = obj as MyStuff; return (other.Id == Id && other.MyValue == MyValue && other.Equals(other.Name, Name)); // use .Equals() here to compare objects; == for Value types // alternative weak Equals() for value objects: // return (other.MyValue == MyValue && other.Equals(other.Name, Name) ); } }
Comments
![RSS Feed for Comments RSS Icon](/images/rss.png?v3)