HRESULT static fields not easily usable in switches
riverar opened this issue · comments
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
- CsWin32 version: 0.3.49-beta
- Win32Metadata version (if explicitly set by project):
- Target Framework: net8.0-windows10.0.19041.0
LangVersion
(if explicitly set by project): [e.g.9
]
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:
- 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.
- 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.