Twenty
Twenty

Reputation: 5961

Get and Set the underlying value of an Enum

So I am trying really hard to change the underlying number value of an Enum. Take this example:

[Flags]
public enum Foo
{
   Foo = 1,
   Bar = 2,
   FooBat = 4
}

With a simple extension methods for enums. In his method I want to remove all flags from the enum itself:

public static TEnum GetBaseVersionOfEnum<TEnum>(this TEnum enumVal) where TEnum : Enum
{
   var tempEnum = enumVal & 0 // I would like to do something like that. e.g. setting its underlying value to zero.
   return tempEnum;
}

Note that it is possible to set an enum to zero, even if there is no matching enum member.

To clarify what I want to achieve, here a few samples:


I actually achieved that, but it is hella ugly, at least IMO, by using some reflection. I really hope there is a cleaner and faster way to do this.

var dynamicVal = (dynamic)enumVal;

dynamicVal.value__ = 0;

var tempEnum = (Enum)dynamicVal;

I actually stumbled over the value__ field by some testing with reflection, which revealed that there is actually a public field which exposes the current value.

This also makes me wonder why you can't access it by using the dot (enumVal.value__)... I guess it is some kind of runtime field.

Upvotes: 1

Views: 191

Answers (1)

V0ldek
V0ldek

Reputation: 10623

I might be deeply confused by your question, but to me it seems you're trying to make a convoluted way of saying default:

public static TEnum GetBaseVersionOfEnum<TEnum>(this TEnum enumVal) where TEnum : Enum
{
    return default;
}

The default value for an enum is all-zero bits (the default for the underlying value type). But why do you need a helper for that at all? You can literally say

Foo allzero;

And you get an all-zero enum of your type. Or say

myExistingEnum = default;

to zero an existing variable out.

Upvotes: 1

Related Questions