Visual Studio 2015 debugger showing null when object is not null

随声附和 提交于 2019-12-13 14:07:31

问题


If I run the following (admittedly contrived) program (VS2015, .NET4.6):

class Program
{
    static void Main(string[] args)
    {
        TestTaskAsync(null).Wait();
        TestTask(null);
    }

    public static async Task TestTaskAsync(
        EqualityComparer<int> comparer)
    {
        comparer = EqualityComparer<int>.Default;

        if (comparer == null)
        {
            Console.WriteLine("comparer is null");
        }

        Func<int, bool> func = i => comparer.Equals(i, 0);
    }

    public static Task TestTask(
        EqualityComparer<int> comparer)
    {
        comparer = EqualityComparer<int>.Default;

        if (comparer == null)
        {
            Console.WriteLine("comparer is null");
        }

        Func<int, bool> func = i => comparer.Equals(i, 0);

        return Task.CompletedTask;
    }
}

then the program does exactly what I expect it to - i.e. it prints nothing to the console.

However, when debugging, the debugger is telling me that comparer is null when it is not.

Note the following:

  • The code does not enter the if block.
  • The two debug values (both pinned and in the watch window) tell me
    that comparer is null, even though it does not enter the if block.
  • The squiggly line and the greyed out code is telling me that
    comparer == null can never be true. Which is correct, I think.
  • This only happens in the method marked async.

Finally, if I remove the line

Func<int, bool> func = i => comparer.Equals(i, 0);

Then the problem goes away.

(Note. The point of the above program is to illustrate a problem I'm having in code that actually does something useful. This program is not actually expected to do anything.)

QUESTION: Does anyone know what is happening here?

来源:https://stackoverflow.com/questions/37411105/visual-studio-2015-debugger-showing-null-when-object-is-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!