简体   繁体   中英

C#: Object is both null and not null

I'm getting some extremely weird behavior. An object appears to be null and not null at the same time, and a statement is getting skipped. I'm probably being an idiot, but if it's my fault I don't see it. I'm building using Visual Studio 2008 on a Windows 7 SP1 OS.

    public void ReadTrendData(OpcDriver opcDriver)
    {
        if (opcDriver != null)
        {
            int a = 1;
        }

        if (opcDriver == null)
        {
            Exception ex = new Exception("Null OPC driver received by ReadTrendData()");
            throw ex;
        }

The opcDriver object is successfully created and passed in to this method. When I step through, the "int a = 1" statement is executed. Then, in the next if block, execution gets to the "throw ex" statement without executing the line above that creates the ex object. So, ex is null and throwing null gives me an access violation exception.

Do you have any idea what could be happening here?

A couple of members of the OpcDriver class are instances of classes from a 15-year-old ungauranteed, unsupported sample library that uses COM to interface with an OPC (OLE for Process Control) program. The only thing I can think of is that somewhere in the bowels of that library something grotesque is happening, but I can't think how this can be possible.

Thank you.

You should try on newer visual studio build. I got almost the same problem on 2008 and 2012 versions. It's a visual studio compile time bug. You should check your build option, if you selected "release" mode you should check back to debug and try again.

To sum up, it probably the problem's root is wrong operator overloading (== and/or !=). The test if (Object.ReferenceEquals(opcDriver, null)) works as expected.

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