4

I'm creating a COM class in C#, which will be called from unmanaged C++. I want to use ThrowExceptionForHR but I'd rather not have to hard-code HRESULT numeric values.

I was expecting there would be some enum of common HRESULT values in .Net somewhere?

Put another way, where can I find named symbols which map to HRESULT values to pass into ThrowExceptionForHR?

Update:

MS talk about it in this page: HRESULT Information in Managed Code. They reference VSConstants class Microsoft.VisualStudio.VSConstants but when I try to use this, it claims that namespace doesn't exist.

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • Search the reference source for one? http://referencesource.microsoft.com/#q=E_NOTIMPL – Alex K. Oct 09 '15 at 11:32
  • It seems like there are loads of them! – Mr. Boy Oct 09 '15 at 13:12
  • I don't think the marked question is a dupe. I am not after an enumeration specifically, just any named values so I can avoid entering raw numeric values. As @AlexK. points out some symbols _do_ exist but it's unclear which class I should be using. – Mr. Boy Oct 09 '15 at 13:22
  • To use the `VSConstants` class you must install the following package: https://www.nuget.org/packages/Microsoft.VisualStudio.Shell.14.0/ – Rosberg Linhares Jun 20 '16 at 19:09

1 Answers1

3

Yes, .NET predefines HRESULT values. You use them by not helping, throw a standard .NET exception just the way you would do it if a managed program uses your library. The exception's HResult property value sometimes matches a common HRESULT value if the match is obvious (like OutOfMemoryException == 0x800700E), in general a 0x8013xxxx value.

The xxxx values are widely documented and listed in the CorError.h SDK header file. IErrorInfo::GetDescription() gives you the exception's Message property value. Automagically localized, nice. You can't get the holy stack trace.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • This is very useful information but - assuming I want/need to use `ThrowExceptionForHR` does .NET have predefined symbols for common HRESULT values, and where can I find them? I edited my question slightly accordingly. – Mr. Boy Oct 09 '15 at 13:16
  • They are baked into the source code for the various exception classes. Use referencesource.microsoft.com if you want to see it. The point was that you should not want to see it. – Hans Passant Oct 09 '15 at 13:25
  • I can see that's generally the case but the fact is, MS provide this API method as a way to send failures to C++ via interop. I found this page: https://msdn.microsoft.com/en-us/library/bb164625.aspx – Mr. Boy Oct 09 '15 at 13:30
  • Sure, you can use it if you want to hard-code an HRESULT value. What you did not want to do. – Hans Passant Oct 09 '15 at 13:48
  • It's possible to [get the stack trace](http://stackoverflow.com/a/33640660/1768303), too. – noseratio Nov 10 '15 at 22:14