The object is null, however if it returns null false

In C # 4.5, I am having a strange problem.

I have this in my model:

private DataMatrix<T> _matrix;

public DataMatrix<T> Matrix
{
    get { return _matrix; }
    set { _matrix = value; }
}

And I have a property that uses this:

public object SingleElement
{
     get
     {
        if (Matrix == null) return String.Empty;

        if (Matrix.ColumnCount >= 1 && Matrix.RowCount >= 1)
        {
           return Matrix[0, 0];
        }
        return null;
     }
 }

When I started it, before calling the SingleElementMatrix property is null. But it does not return String.Empty, it goes to the second if statement.

My Immediate window says: Immediate window

I'm a little confused. What have I done wrong?

+4
source share
1 answer

This is most likely a broken equality operator ( ==), which can be reproduced using the following code:

class Foo
{
    public static bool operator == (Foo x, Foo y)
    {
        return false; // probably more complex stuff here in the real code
    }
    public static bool operator != (Foo x, Foo y)
    {
        return !(x == y);
    }
    static void Main()
    {
        Foo obj = null;
        System.Diagnostics.Debugger.Break();
    }
    // note there are two compiler warnings here about GetHashCode/Equals;
    // I am ignoring those for brevity
}

now at the breakpoint in the nearest window:

?obj
null
?(obj==null)
false

Two fixes:

  • it would be preferable to fix the statement, perhaps by adding before anything else:

    if(ReferenceEquals(x,y)) return true;
    if((object)x == null || (object)y == null) return false;
    // the rest of the code...
    
  • , , , ; ReferenceEquals object -based null; :

    if(ReferenceEquals(Matrix, null)) ...
    

    if((object)Matrix == null) ...
    
+6

Source: https://habr.com/ru/post/1540358/


All Articles