Implementing IEquatable, IComparable, operators and Object overrides For A ValueType
CodeKeep C# Feed Aprile 28th, 2008
Description: Implementing IEquatable, IComparable, operators and Object overrides For A ValueType
Link: http://www.codekeep.net/snippets/4facb52e-b2da-4b84-b896-2cb7b341d66f.aspx
public struct MyValue : IComparable<MyValue>, IEquatable<MyValue>
{
int theValue;
public int CompareTo(MyValue other)
{
return theValue - other.theValue;
}
public bool Equals(MyValue other)
{
return CompareTo(other) == 0;
}
public override bool Equals(object obj)
{
if (!(obj is MyValue))
{
throw new ArgumentException("Not MyValue type.");
}
return Equals((MyValue)obj);
}
public override int GetHashCode()
{
return theValue.GetHashCode();
}
public static bool operator ==(MyValue leftHandValue, MyValue rightHandValue)
{
return leftHandValue.Equals(rightHandValue);
}
public static bool operator !=(MyValue leftHandValue, MyValue rightHandValue)
{
return !leftHandValue.Equals(rightHandValue);
}
public static bool operator <(MyValue leftHandValue, MyValue rightHandValue)
{
return leftHandValue.CompareTo(rightHandValue) < 0;
}
public static bool operator >(MyValue leftHandValue, MyValue rightHandValue)
{
return leftHandValue.CompareTo(rightHandValue) > 0;
}
public static bool operator <=(MyValue leftHandValue, MyValue rightHandValue)
{
return leftHandValue.CompareTo(rightHandValue) <= 0;
}
public static bool operator >=(MyValue leftHandValue, MyValue rightHandValue)
{
return leftHandValue.CompareTo(rightHandValue) >= 0;
}
}






