C# HRESULT comparison
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:
try{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 serverif (this.LoadServer())
return this.CallComServer();
}
this.ErrorMessage = ex.Message;return false;
}
catch (Exception ex)
{ this.ErrorMessage = ex.Message;return false;
}
finally{ this.EndRequest();}
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>...
Other Posts you might also like
- Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application
- Resolving Paths To Server Relative Paths in .NET Code
- Map Physical Paths with an HttpContext.MapPath() Extension Method in ASP.NET
- Getting the ASP.NET Core Server Hosting Urls at Startup and in Requests
- Back to Basics: Rewriting a URL in ASP.NET Core
The Voices of Reason
# re: C# HRESULT comparison
# re: C# HRESULT comparison
# re: C# HRESULT comparison
# 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 )
# re: C# HRESULT comparison