Compare Hex value to Integer returned by function



    I'm using System.Runtime.interopServices.Marshal.GetHRForException(Exception) and it returns the HRESULT as an integer.  Trying to represent possible HRESULT values as hex constants, rather than negative int values.


    const int NO_MEDIA = -1062600190;  //want this to be the hex value 0xC0AA0202


    int HResult = System.Runtime.interopServices.Marshal.GetHRForException(Exception);



    The above code works.  But when I try to set NO_MEDIA to the hex value 0xC0AA0202(using the code below), I get OverflowException. 


    const uint NO_MEDIA = 0xC0AA0202;

    uint HResult = Convert.ToUInt32(System.Runtime.interopServices.Marshal.GetHRForException(Exception));



    Wednesday, January 16, 2008 6:13 PM


  • The Convert function is viewing it as a negative decimal number.  Unsigned integers cannot store negatives, so you get the overflow.

    The solution is to use an unchecked cast.

    uint HResult =unchecked((uint)

    Since this is a runtime conversion, "unchecked" isn't required unless you're doing a checked build (not the default), but it's still a good practice to have it to indicate that you're ignoring the sign bit for the conversion.

    -Ryan / Kardax
    Wednesday, January 16, 2008 7:09 PM