Alex Rivera | Logout

Overriding C# Conditional statements problem

Asked 2009-08-20T03:13:42.737
17

I was writing some code today and something was not working as I expected.

Why does the following code execute even though the condition should have evaluated to false?

alt text http://img215.imageshack.us/img215/3011/agfewrf.gif

I have tried putting braces around the two conditions, and switching their position, but the EndedUsingApplication even still executes.

EDIT:

It has nothing to do with the || or && operators. Look at this...

alt text

Nobody can learn from my mistake unless I post the culprit code, so here it is.

  public static bool operator ==(ActiveApplication a, ActiveApplication b)
     {
     if ((object)a == null || (object)b == null)
        return false;
     return a.process_name == b.process_name && a.window_title == b.window_title;
     }

  public static bool operator !=(ActiveApplication a, ActiveApplication b)
     {
     return a == b ? false : true;
     }

And here is the working 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 && (object)b == null)
        return true;
     if ((object)a == null ^ (object)b == null)
        return false;
     return a.process_name == b.process_name && a.window_title == b.window_title;
     }

  public static bool operator !=(ActiveApplication a, ActiveApplication b)
     {
     return a == b ? false : true;
     }

The problem appeared to be when the != operat

Edit
Report

1 Answer

1

I think a better approach is to use Object.ReferenceEquals as it is more explicit:

public static bool operator ==(ActiveApplication a, ActiveApplication b)
     {
     // same reference so equals is true - will be true for null == null
     if (object.ReferenceEquals(a, b))
        return true;

     // one is null and the other is not
     if (object.ReferenceEquals(a, null) || object.ReferenceEquals(b, null))
        return false;

     // dealt with all combinations of null - compare fields
     return a.process_name == b.process_name && a.window_title == b.window_title;
     }

  public static bool operator !=(ActiveApplication a, ActiveApplication b)
     {
     return !(a == b);
     }
answered 2009-08-21T03:11:50.460

Your Answer