Thursday, October 04, 2007

Overriding operators in C#

In one of my projects, i thought i'd love to use operators like ==, !=, > and < style="color: rgb(51, 51, 255);font-size:85%;" > public static bool operator ==(BaseEventVO evt1, BaseEventVO evt2)
{
return (((object)evt1 == (object)evt2) || ((object)evt1 != null) && ((object)evt2 != null) && evt1.IdSeq == evt2.IdSeq && evt1.Year == evt2.Year);
}

public static bool operator !=(BaseEventVO evt1, BaseEventVO evt2)
{
return !(evt1 == evt2);
}

public static bool operator >(BaseEventVO evt1, BaseEventVO evt2)
{
return (evt1.Year > evt2.Year || (evt1.Year == evt2.Year && evt1.Day > evt2.Day));
}

public static bool operator <(BaseEventVO evt1, BaseEventVO evt2)
{
return (evt1.Year < evt2.Year || (evt1.Year == evt2.Year && evt1.Day < evt2.Day));
}


Notice the cast to "(object)evt1 != null" - it is necessary in order to prevent loopback - you can't do "evt1 != null" as it'd use the "!=" overridden operator, hence ending in effective infinite loop (until call-stack blows).

You may also want to override GetHashCode() to produce unique ID of the object - speeds up things very significantly when you do hashtable lookups.

No comments: