Search code examples
c#.netcom

Convert argument exception to HRESULT?


I am developing a Microsoft .NET assembly to be consumed by Microsoft .NET and COM components. I am writing managed code and must indicate when incorrect arguments are specified for methods within the class. I need to return control back to COM componments with the proper error when an argument exception occurs.

Say the code is:

throw new ArgumentException("Invalid Argument");

I guess that the code throws a new ArgumentException object that can be consumed as is by Microsoft .NET components and converted by the CLR into an HRESULT for COM components. Managed code indicates errors or abnormal events as exceptions, while COM components except hexadecimal error code known as HRESULTs.

My question is what is hexadecimal value for this ArgumentException? If it is COR_E_ARGUMENT or E_INVALIDARG, then it is doesn't matter with the specified error message?(Here is "Invalid Argument")


Solution

  • It is both, COR_E_ARGUMENT and E_INVALIDARG have the same numerical value. Use the Reference Source to see how the class initializes its HResult property value. Click through to __HResults.COR_E_ARGUMENT to see 0x80070057, which is Windows' ERROR_INVALID_PARAMETER error code packed into an hresult. You can obtain the error code for E_INVALIDARG from the WinError.h SDK header file, same value.

    It depends on how the client code obtains a textual description for the error, hopefully it uses IErrorInfo to obtain the Exception.Message property. But if it doesn't then there are some odds that it uses FormatMessage(). Which produces the Windows error code description, "The parameter is incorrect".