开发者

C# - null vs "Could not evaluate expression"

I have code like this:

    private Box mCurBox;

    public Box CurBox
    {
        get { return mCurBox; }
        set
        {
    开发者_如何学Python        if (mCurBox != value)
            {
                mCurBox = value;
            }
        }
    }

When mCurBox is null then CurBox the debugger says "Could not be evaluated". If it knows that the value underneath is null then how come it can't figure it out?


That's because you have not defined mCurBox to be anything by default, so the compiler flags this as undefined behaviour.
You need to initialize mCurBox as null, either in the very same line you define it, or in a constructor.
In general, it's good practice to initalize reference types to null if you don't assign something to them when defining them.
Also, seeing as you're just assigning and retrieving, you can easily use auto properties.


The debugger can get gimpy now and then. But the expected case of getting "Could not be evaluated" is a Release build. Simple properties like this get optimized away by the JIT compiler. The property getter code would not even be present.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜