Entity Framework object is not null, but `== null` returns true

My code is:

var x = myEntities.MyTable
                  .Include("MyOtherTable")
                  .Include("MyOtherTable.YetAnotherTable")
                  .SingleOrDefault(c => c.Name == someName);

Correctly returns an object that I can view in intellisense in visual studio, as correct.

Next line:

if (x == null)
{
}

However, this statement returns true, and the code inside {}is executed. What can cause this?

Edit:

Added this line above the zero check:

var someName = x.Name;

This code works fine, and someName becomes stringwith the name of the object in it.

== null still returns true.

IDE Screenshots:

enter image description here

enter image description here

edit: the code works in the function:

    public void bibble(MyObjectType s)
    {
        if (s == null)
        {

            throw new Exception();
        }
    }
--
    string someName = testVariable.Name;

    this.bibble(testVariable); // Works without exception

    if (testVariable == null)
    {
        // Still throws an exception
        throw new Exception();
    }

Now it does not evaluate the value truein another method, but does it in the main method for the same variable. So strange.

Edit: Here is the IL for this section:

  IL_0037:  callvirt   instance string [MyLibrary]MyLibrary.MyCompany.MyObjectType::get_Name()
  IL_003c:  stloc.3
  IL_003d:  ldarg.0
  IL_003e:  ldloc.2
  IL_003f:  call       instance void MyOtherLibrary.ThisClass::bibble(class [MyLibrary]MyLibrary.MyCompany.MyObjectType)
  IL_0044:  nop
  IL_0045:  ldloc.2
  IL_0046:  ldnull
  IL_0047:  ceq
  IL_0049:  ldc.i4.0
  IL_004a:  ceq
  IL_004c:  stloc.s    CS$4$0001
  IL_004e:  ldloc.s    CS$4$0001
  IL_0050:  brtrue.s   IL_0059
  IL_0052:  nop
  IL_0053:  newobj     instance void [mscorlib]System.Exception::.ctor()
  IL_0058:  throw

Edit: Even MORE weird:

var myEFObjectIsNull = testVariable == null;

// Intellisense shows this value as being FALSE.

if (myEFObjectIsNull)
{
    // This code is ran. What.
    throw FaultManager.GetFault();
}
+4
1

, == . ==(MyTable,MyTable) null:

static class Program {
    static void Main() {
        Foo x = new Foo();
        if(x==null) {
            System.Console.WriteLine("Eek");
        }
    }
}

public class Foo {
    public static bool operator ==(Foo x,Foo y) {
        return true; // or something more subtle...
    }

    public static bool operator !=(Foo x, Foo y) {
        return !(x==y);
    }
}
+5

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


All Articles