简体   繁体   中英

Method returning a non-null value still assigns null to a variable

I have a method that searches something in my database according to a field. when calling that method and saving the returning value in a variable, the returning value is not null at the end of the function. After the function has been called and I debug what is available in my variable, the value is still null!

In one class I have:

var box = _someClass.GetBoxByRfidAsync("testvalue");
public Box GetBoxByRfidAsync(string rfid)
{
    var foundBox = _dc.Boxes
        .Include(b => b.Stack)
        .Include(b => b.Type)
        .Where(box => box.RFID1 == rfid)
        .FirstOrDefault();

     return foundBox;
}

The box class looks like this:

public class Box
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string RFID1 { get; set; }
    public string Rit { get; set; }
    public Stack Stack { get; set; }
    public int PosInStack { get; set; } //lowest box is 0, highest is 7
    public BoxType Type { get; set; }
    public DateTime Inserted { get; set; }

}

The method gets executed and at the end of GetBoxByRfidAsync I can see using the debugger that foundBox is NOT null.

I step over the end of the function and go to the assignment of the foundBox value to the box variable. For some reason the 'box' variable stays null and does not change.

The box variable should be equal to the foundBox value, but it stays null.

Here are some screenshots of my debugging session:

方法结束 即时窗口显示框仍为空

The error you show in the debugger doesn't mean that box is null . If box was null , it would literally just report: null .

Instead, the box is non- null , and something that the debugger is evaluating to display the value is throwing an exception. Perhaps a broken ToString() . The fact that it mentions ListDictionaryInternal means that you might want to look in particular at any collection or dictionary usage inside the type, and perhaps anything that is marked with "debugger" attributes such as [DebuggerDisplay(...)] .

If you want to test whether box is null , ask the immediate console:

box == null

and it will return true or false (caveat: assuming that there isn't a broken static equality operator, which is also possible; to avoid that, a good alternative is:

box is object

which will reliably return true if it is non- null , and false if it is null , without using static equality operators.


Edit: based on the discussion in the comments, I'm overwhelmingly convinced that this is a broken == operator, as demonstrated here:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM