Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding C# Conditional statements problem
    primarykey
    data
    text
    <p>I was writing some code today and something was not working as I expected.</p> <p>Why does the following code execute even though the condition should have evaluated to false?</p> <p><a href="http://img215.imageshack.us/img215/3011/agfewrf.gif" rel="nofollow noreferrer">alt text http://img215.imageshack.us/img215/3011/agfewrf.gif</a></p> <p>I have tried putting braces around the two conditions, and switching their position, but the EndedUsingApplication even still executes.</p> <p>EDIT:</p> <p>It has nothing to do with the || or &amp;&amp; operators. Look at this...</p> <p><a href="http://img20.imageshack.us/img20/6655/aaaaaal.gif" rel="nofollow noreferrer">alt text http://img20.imageshack.us/img20/6655/aaaaaal.gif</a></p> <p>Nobody can learn from my mistake unless I post the culprit code, so here it is.</p> <pre><code> public static bool operator ==(ActiveApplication a, ActiveApplication b) { if ((object)a == null || (object)b == null) return false; return a.process_name == b.process_name &amp;&amp; a.window_title == b.window_title; } public static bool operator !=(ActiveApplication a, ActiveApplication b) { return a == b ? false : true; } </code></pre> <p>And here is the working code ...</p> <pre><code> public static bool operator ==(ActiveApplication a, ActiveApplication b) { // Casting to object class prevents this comparison operator being executed // again and causing an infinite loop (which I think .NET detects and stops // but it would still be a huge hole in the logic. if ((object)a == null &amp;&amp; (object)b == null) return true; if ((object)a == null ^ (object)b == null) return false; return a.process_name == b.process_name &amp;&amp; a.window_title == b.window_title; } public static bool operator !=(ActiveApplication a, ActiveApplication b) { return a == b ? false : true; } </code></pre> <p>The problem appeared to be when the != operator received two null values.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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