I have simple class only with public string properties.
public class SimpleClass
{
public string Field1 {get; set;}
public string Field2 {get; set;}
public string Field3 {get; set;}
public List<SimpleClass> Children {get; set;}
public bool Equals(SimpleClass simple)
{
if (simple == null)
{
return false;
}
return IsFieldsAreEquals(simple) && IsChildrenAreEquals(simple);
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this); //Bad idea!
}
}
This code doesn't return same value for equal instances. But this class does not have readonly fields for compute hash.
How can i generate correct hash in GetHashCode() if all my properties are mutable.
GetHashCode()to determine a hash for that moment in time, not for the lifetime of that object. If you want the latter, then indeed you must make the properties read-only.SimpleClassas a key in a dictionary, what do you want to happen when one of those properties gets modified? If that causes the hash code to change, the dictionary will break. You may say "I won't do that", but you should be the one to actually say that, we shouldn't silently assume it.