Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

C# HRESULT comparison

On this page:

I just had a little brain freeze dealing with an HRESULT error from a COMException. When dealing with COM objects you still need to deal with the unfortunate COM idiosyncrasies like HRESULT values which get returned from just about every COM call.

COMException exposes this HRESULT as an int value in the Exception's ErrorCode property. Now in my brain freeze haze I tried something like this:

    this.OutputBuffer = this.ComInstance.GetType().InvokeMember("ProcessHit", BindingFlags.InvokeMethod,
                                                                null, this.ComInstance, 
                                                                new object[1] { this.CompleteInputBuffer }) as string;
catch (COMException ex)
    // *** RPC Server Unavailable 
    if ( ex.ErrorCode == 0x800706ba ) 
        // try to reload the server
        if (this.LoadServer())
            return this.CallComServer();
    this.ErrorMessage = ex.Message;
    return false;
catch (Exception ex)
    this.ErrorMessage = ex.Message;
    return false;

Now that seems like it should work well enough right? 

Eh, not quite. The problem is that the constant hex value is created as a uint while the HRESULT is a signed integer. The code compiles just fine but at runtime the comparision may fail (depending on the HRESULT's actual value - high values like the one above (and aren't just about all COM errors 0x800... <s>) will fail.

So quick - how do  you create a signed hex constant?

I don't know, but this works as expected:

if ( (uint) ex.ErrorCode == 0x800706ba ) 

Hopefully this will save somebody the 15 minutes I just wasted on this <s>...

Posted in .NET  COM  

The Voices of Reason


June 20, 2007

# re: C# HRESULT comparison

Thanks!! You just saved me 15 minutes as well!!!

August 29, 2007

# re: C# HRESULT comparison

You saved me some time too- thanks!

May 06, 2008

# re: C# HRESULT comparison

Another 15 minutes saved. That's a grand total of 45 minutes now :)

April 28, 2009

# re: C# HRESULT comparison

Thanks a lot... You also saved me some time. :)

April 20, 2011

# re: C# HRESULT comparison

if ( (uint) ex.ErrorCode == 0x800706ba )

this will not work. throws an OverflowException, depending on the value of ex.ErrorCode (at least it did in my case).

to prevent the runtime from doing the overflow-check when casting, do this:
if ( unchecked ( (uint) ex.ErrorCode ) == 0x800706ba )

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024