Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting an operator overload in C#, for a complex type, which relies on the operator itself
    text
    copied!<p>I have a complex type called "HalfDay" which is a combination of a DateTime and an Enum value to represent either AM/PM.</p> <pre><code>public class HalfDay { private DateTime _Date; public DateTime Date { get { return _Date; } set { _Date = value.Date; } } private DayHalf _Half; public DayHalf Half { get { return _Half; } set { _Half = value; } } } </code></pre> <p>I am trying to write a set of overloaded operators to compare two HalfDays.</p> <pre><code> public static bool operator &lt;(HalfDay halfday1, HalfDay halfday2) { if (halfday1.Date.Date &lt; halfday2.Date.Date) return true; if (halfday1.Date == halfday2.Date &amp;&amp; halfday1.Half &lt; halfday2.Half) return true; return false; } public static bool operator &gt;(HalfDay halfday1, HalfDay halfday2) { if (halfday1.Date.Date &gt; halfday2.Date.Date) return true; if (halfday1.Date == halfday2.Date &amp;&amp; halfday1.Half &gt; halfday2.Half) return true; return false; } public static bool operator ==(HalfDay halfday1, HalfDay halfday2) { if (halfday1 == null &amp;&amp; halfday2 == null) return true; if (halfday1 == null || halfday2 == null) return false; return halfday1.Date.Date == halfday2.Date.Date &amp;&amp; halfday1.Half == halfday2.Half; } public static bool operator !=(HalfDay halfday1, HalfDay halfday2) { if (halfday1 == null &amp;&amp; halfday2 == null) return false; if (halfday1 == null || halfday2 == null) return true; return !(halfday1 == halfday2); } </code></pre> <p>In true newbie style (I've never written operators before) I've used the == comparison to compare a HalfDay with null. The result is, of course, a stack overflow as my operator code gets called recursively.</p> <p>I think I need to check for null in my operators to correctly return false (or true) for comparisons being made where either of the arguments is null. I've clearly misunderstood something fundamental about OOP though - any pointers on how I should correctly write these operators?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload