microsoft / CsWin32

A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.
MIT License
1.99k stars 84 forks source link

HRESULT static fields not easily usable in switches #1100

Closed riverar closed 6 months ago

riverar commented 6 months ago

Actual behavior

switch(...)
{
-   case HRESULT.S_OK:
    default:
        throw new NotImplementedException();
}
Error CS9135 A constant value of type 'HRESULT' is expected

Expected behavior

Naturally switch on HRESULT values against compile-time statics.

Context

AArnott commented 6 months ago

Oh boy, I wish we could.

But C# doesn't allow defining constants typed as a custom struct. That as you see in the error precludes them from being used in a switch statement. If HRESULT was an enum it would work, but after a long discussion it was decided that HRESULT should not be expressed as an enum for a few reasons, including:

  1. Enums convey an idea of an exhaustive list of allowed values. This isn't actually true, but it almost always is. But HRESULT is fundamentally an 'open' type, where no exhaustive list of allowed values can be defined.
  2. Enums do not support custom members such as methods or conversion operators, which would make HRESULT much less user friendly in some cases. Extension methods can be defined, but this cannot adequately fill the gap.

So I'm afraid C# forces code to use if statements instead.