Adam Driscoll
Adam Driscoll

Reputation: 9483

Changing a flag based on a boolean

Does any have a more elegant way of doing this?

[Flags]
public enum SomeFlaggedEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 4
}


private SomeFlaggedEnum _myFlags;

public bool EnabledValue1
{
    set 
    {
        if (value)
        {
            _myFlags |= SomeFlaggedEnum.Value1;
        }
        else
        {
            _myFlags &= ~SomeFlaggedEnum.Value1;
        }
    }
} 

I know there is probably a simple answer and I'm just way over thinking it...

EDIT: The enum was incorrect as pointed out in one of the answers. This was only in this example and not in the actual code.

Upvotes: 7

Views: 6045

Answers (5)

Anders Forsgren
Anders Forsgren

Reputation: 11101

Make a generic setter for flags (there is already a generic "HasFlag" in the Enum class, but an extension like this will complement it.

public static class EnumExtensions
{
    public static T SetFlags<T>(this T value, T flags, bool on) where T : struct
    {    
        long lValue = Convert.ToInt64(value);
        long lFlag = Convert.ToInt64(flags);
        if (on)
        {
            lValue |= lFlag;
        }
        else
        {
            lValue &= (~lFlag);
        }
        return (T)Enum.ToObject(typeof(T), lValue);
    }
}

Once you have that, you can make properties for each flag (but that quickly gets messy), or simply delegate getting and setting flags to HasFlag/SetFlag

Upvotes: 3

Mark H
Mark H

Reputation: 13897

It looks like it'd get pretty ugly if you had a property per flag for setting it, assuming you'll have more than 3 flags. Would it not be easier to go for a single method where you can say which flags to set?

public void EnableFlag(SomeFlaggedEnum value, bool set) {
    _myFlags = set ? value | _myFlags : ~value & _myFlags;
}

EnableFlag(SomeFlaggedEnum.Value1, true);

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283614

Your setter is fine.

The issue is that using FlagsAttribute doesn't make the compiler choose useful values for using the enum members as flags. SomeFlaggedEnum.Value1 is zero, because it's the first declared value in the enumeration, and so it doesn't represent a bit flag at all.

Try

[Flags]
public enum SomeFlaggedEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 4
}

Upvotes: 2

i_am_jorf
i_am_jorf

Reputation: 54600

I mean, you could do:

_myFlags = value ? myFlags | SomeFlaggedEnum.Value1 : myFlags & ~SomeFlaggedEnum.Value1;

But I think your solution is fine.

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1500015

Well, you could use a conditional:

_myFlags = value ? _myFlags | SomeFlaggedEnum.Value1
                 : _myFlags & ~SomeFlaggedEnum.Value1;

Upvotes: 6

Related Questions