I recently came about this problem. I have a base Stamp
class. Then I made two inherited classes OwnedStamp
and AuctionStamp
. I overrided the Equals
and GetHashCode
method in Stamp
class like this:
public override bool Equals(object obj)
{
if(obj == null || this.GetType().Equals(obj.GetType()))
{
return false;
}
else
{
Stamp stamp = obj as Stamp;
return this.Title == stamp.Title;
}
}
public override int GetHashCode()
{
return Title.GetHashCode();
}
I also have overloaded these operators in the same class:
public static bool operator ==(Stamp lhs, Stamp rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(Stamp lhs, Stamp rhs)
{
return !lhs.Equals(rhs);
}
Then I have this scenario:
OwnedStamp checkStamp = check.GetStampByTitle(stampTitle);
if(checkStamp != null && checkStamp.Price <= toCompare.Price)
{
picked.Add(check);
}
The checkStamp
is not null
and it holds the correct informtaion I need, but when i check for the equality for null
it throws me the exception. I have other lines with code where I check for equality between two stamps of any type. I have tried couple of different Equals method realizations. The problem consists. I have red that checking equality in base class even if we pass child class to the method shouldn't be a problem. Any help would be apreciated!