In C#, how do I get the descriptive text for an HRESULT?

Raymond Chen

Suppose your C# code manages to find in its hands a COM HRESULT value. How do you convert that to a descriptive string?

One idea is to p/invoke to the Format­Message function, but that’s awfully cumbersome. Maybe we can live off the land.

using System;
using System.Runtime.InteropServices;

class Program
    public static string MessageFromHResult(int hr)
        return Marshal.GetExceptionForHR(hr).Message;

    public static void Main()
        var E_BOUNDS = unchecked((int)0x8000000B);

The result:

The operation attempted to access data outside the valid range (Exception from HRESULT: 0x8000000B)

We ask the Marshal class to create an exception from the HRESULT and extract the Message from it. This does do more work than necessary, because it also does additional exception-related stuff, like capturing the COM error context into the exception object. This is wasted work, but on the other hand, the convenience is hard to beat.