Category name´╝ÜHRESULT

Why is the ErrorCode property of type int?

Once in a while you need to handle an framework exception that has an ErrorCode property. The HttpException and COMException classes for example have such a property. The problem here is that the Message property contains the ErrorCode in hex but the ErrorCode property is of type int which is signed. It is probably int to be CLS complaint or something but it always gives me a headache!

Everytime I do something like:

const int DISP_E_BADINDEX = 0x8002000B;  // Cannot assign uint to int

But that fails because 0x8002000B is an unsigned value but that value is just copied from the Message property text. So now you first need to convert it to a signed int like the following:

const int DISP_E_BADINDEX = (int)0x8002000B;  // Cannot cast uint to int use unchecked keyword.

*Sigh* doesn’t this give you a headache? So the final code is:

unchecked
{
    const int DISP_E_BADINDEX = (int)0x8002000B;
    ….
}

But that is also not very neath as the constant int value can now only be used in one method while in most scenarios this value is declared as a constant data member. So now I just start Snippet compiler and dump the signed integer result of the cast and copy paste that in my code like the following line:

const int DISP_E_BADINDEX = -2147352565; // HRESULT 0x8002000B

No bloated code but this.. It would have been nice if it was possible to directly assign such a hex value to a int.

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta