MyClass myClass = new MyClass("hello world");
Is shorter than saying:
MyClass myClass = new MyClass();
myClass.Text = "hello world";
But the other day I was once again overriding the GetHashCode method for a .NET class because I had overridden the Equals method and you should override both at the same time. Usually I just don't care much about this method and write some probably incredible poor hashing method (aka, GetHashCode of some properties)
Well, I decided to do a bit of a Google for a proper hash method. I actually found some very interesting proposals and looked to implement some of them. All of the methods of overriding GetHashCode look at using the fields in the class to develop a unique hash.
Now, the important thing about the GetHashCode method is that the result from it must be immutable for the class. Since we are basing our hash off of some class fields, those fields must now also be immutable.
Let's say you have a class called Person. It would seem reasonable that the hash code be based upon the person's name. Every class with a name of John Doe should generate the same hash code.
But here in comes the problem, what if the name changes? We want the GetHashCode to always return the same thing for the class and we need the name to be immutable now. This is especially important if that class is added to a list or becomes a key to a dictionary.
And so here I was lead to my "AH HA!" moment. Parameters passed in with the constructor should be considered immutable and define the class for its life time. Any constructor parameter should not be allowed to be changed after the instantiation of the class. This way the GetHashCode always returns the same value regardless. So, my person class gets a constructor of Person(string firstName, string lastName). Now forever going forward those two properties are fixed to the class and the GetHashCode always works.
Class fields that are accessed via set properties (or setXXX methods) are mutable and therefore cannot be used for hashing. So, for my Person I may have mutable properties, but the name is now considered fixed.
Person myPerson = new Person("Jane", "Doe");
myPerson.Slogan = "Hello World!!!";
In this case, the name is immutable, whereas the slogan is not. The slogan cannot participate in hashing.