Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Enum with flag methods?

I have found good examples on how to create extension methods to read out single values from bitwise enums. But now that C# 4 has added the HasFlag method they are really not needed.

What I think would be really helpful though is an extension to SET a single flag!
I have many situations where I need to set the flag values individually.
I want an extension method with this signature:

enumVariable.SetFlag(EnumType.SingleFlag, true);

OR possibly:

enumVariable.SetFlag<EnumType>(EnumType.SingleFlag, true);
like image 441
Jakob Lithner Avatar asked May 11 '26 19:05

Jakob Lithner


2 Answers

I've done something that works for me and very simple. Probably not efficient due to dynamic casting usage. But perhaps you could like it?

public static T SetFlag<T>(this Enum value, T flag, bool set)
{
    Type underlyingType = Enum.GetUnderlyingType(value.GetType());

    // note: AsInt mean: math integer vs enum (not the c# int type)
    dynamic valueAsInt = Convert.ChangeType(value, underlyingType);
    dynamic flagAsInt = Convert.ChangeType(flag, underlyingType);
    if (set)
    {
        valueAsInt |= flagAsInt;
    }
    else
    {
        valueAsInt &= ~flagAsInt;
    }

    return (T)valueAsInt;
}
like image 133
Eric Ouellet Avatar answered May 14 '26 08:05

Eric Ouellet


Maybe not as pretty as you'd hoped but you can do it quite simply :)

enumVariable |= EnumType.SingleFlag;
like image 30
Nikola Radosavljević Avatar answered May 14 '26 09:05

Nikola Radosavljević