Are .NET enum types actually mutable value types? Are .NET enum types actually mutable value types? powershell powershell

Are .NET enum types actually mutable value types?


Let me try to make sense of this rather confusing question for readers who are unfamiliar with how enums are generated behind the scenes. The C# code:

enum E { A, B }

becomes the IL

.class private auto ansi sealed E extends [mscorlib]System.Enum{  .field public specialname rtspecialname int32 value__  .field public static literal valuetype E A = int32(0x00000000)  .field public static literal valuetype E B = int32(0x00000001)} 

Or, to rewrite that in C# again, the enum is equivalent to the following pseudo-C#:

struct E : System.Enum{    public int value__;    public const E A = 0;    public const E B = 1;}

The question is: why is the magical field value__ public?

I wasn't around for this design decision, so I'd have to make an educated guess. My educated guess would be: how do you initialize an instance of the struct if the field is not public?

You make a constructor, which you then have to call, and that is giving work to the jitter, and what does the performance cost of that work buy you? If the answer is "it buys me the runtime preventing myself from doing something foolish and dangerous that I shouldn't be doing in the first place and had to work really hard to do at all" then I submit to you that this is not a compelling cost-to-benefit ratio.

Since the instance was in a hashtable and the mutation lead to a change of hash code, the instance is in the wrong "bucket" after the mutation, and the HashSet cannot function.

That's several miles past the "if it hurts when you do that then stop doing that" line.