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
- 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) );
- }
- }
Report this snippet
Tweet
wot - no edit feature?
I stole this from Jonathan McCracken: Test-Drive ASP.NET MCV
My first snippet and probably my last.
The Comments field in the original post is marked up as text - not converted to html.
You expect me to add my own
s and 's ? Crazy. The title is capitalized making it meaningless. GetHashCode() is meaningful, GETHASHCODE() meaningless.
Whoever wrote this program should finish developing it before releasing it upon an unsuspecting world.
Doesn't allow html tags in the comments - crazier!
that should be: <p>'s and <div>'s
The program can't tag something as c#. Is the hash code some specials html markup? - it wasn't the last time I looked.
I found 4 bugs in this program already. Hey - developers finish what you started please.
Editing and comment formating needs a lot of work. We've been slowly working our way through the code now that we've taken over the service.
I've forwarded your problems to our Devs for them to take a look at. Thanks!