Consider these classes:
public class BaseClass {
public int SomeInt { get; set; }
public bool SomeBool { get; set; }
public BaseClass(int i, bool b) {
SomeInt = i;
SomeBool = b;
}
}
public class InheritedClass : BaseClass {
public List<Int32> SomeInts { get; set; }
public InheritedClass(int i, bool b, List<Int32> ints): base(i, b) {
SomeInts = ints;
}
public InheritedClass(BaseClass b, List<Int32> ints) : base(b.SomeInt, b.SomeBool) {
SomeInts = ints;
}
}
And I’ve got an instance of InheritedClass, I want to get the HashCode value of it if it were a BaseClass. I’ve tried casting it:
BaseClass x = new BaseClass(10, true);
Console.WriteLine("HashCode x: {0}", x.GetHashCode());
InheritedClass iX = new InheritedClass(x, new List<int> { 1, 2, 3 });
Console.WriteLine("HashCode iX: {0}", iX.GetHashCode());
BaseClass bX = (BaseClass)iX;
//I've also tried:
//BaseClass bX = ix as BaseClass;
Console.WriteLine("Base HashCode bX: {0}", bX.GetHashCode());
But the final WriteLine is returning the hashcode as if it was an InhertiedClass. I can’t overide the GetHashCode of the InheritedClass, and save constructing a new BaseClass from the properties of the object, is there anyway to get the HashCode I need?
The hashcode for an instance of anything will be the same no matter how you cast it. Irrespective of how you are ‘viewing’ it, you are still looking at the same object in memory. The only way I can think of to do this is to clone it as the base type (so you have an actual instance of the base class) and then hash it.