Skip to content

Add Enum.SetFlag and Enum.RemoveFlag to make bitwise flagging easier #14084

Closed

Description

@yufeih

To maintain multiple bool states in a class, instead of declaring many bool fields, an enum flag can be used to compact these states in to a single member to optimize for memory usage.

[Flags] enum DirtyFlags { X = 1, Y = 1 << 1, Z = 1 << 2 };

DirtyFlags dirtyFlags = DirtyFlags.X | DirtyFlags.Y | DirtyFlags.Z;

It is simple to test if a flag is set using Enum.HasFlag(DirtyFlags.X), but the scenario is not complete. Without the ability to set and remove a flag, the following code needs to be maintained manually:

// Setting a flag
dirtyFlags |= DirtyFlags.X;
// Removing a flag, this is harder to remember :(
dirtyFlags &= ^DirtyFlags.X;

The suggestion is to add 2 methods to Enum to help set and clear a flag.

public bool HasFlag(Enum flag); // This method already exists
public bool SetFlag(Enum flag);
public bool RemoveFlag(Enum flag);

These methods should be aggressively inlined since bitwise manipulations is very likely to be used in a performance sensitive scenario.

Activity

  1. mikedn commented on Feb 8, 2015

    @mikedn
    Contributor

    With the current language and runtime capabilities there's no way to implement SetFlag and RemoveFlag efficiently. Even the existing HasFlag has horrible performance compared to the "manual" way of testing flags.

  2. Alexx999 commented on Feb 9, 2015

    @Alexx999
    Contributor

    @yufeih enum is now implemented in, well, not nice way. It's half-struct half-class which can turn out be any type in practice, and framework uses tons of hacks and quirks to make it work like it should.
    So @mikedn is probably right - it will be hard to make it work fast.
    However, it's probably worth trying.

    UPD: Okay, looked at it for a bit more... I believe not much can be done here without changing specifications for enum. Now, argument for HasFlags is treated as object, so it requires boxing-unboxing and has corresponding performance hit.
    It will not work fast without some serious changes in how enums work (generics?) but that will probably require changes at runtime and/or compilers.

  3. HellBrick commented on Feb 9, 2015

    @HellBrick

    This is another example where enum constraint on a generic argument (dotnet/roslyn#262) would be useful. It would allow something like

    T WithFlags<T>( this T source, T flagsToAdd ) where T: enum { /* ... */ }
    T WithoutFlags<T>( this T source, T flagsToRemove ) where T: enum { /* ... */ }
  4. HaloFour commented on Feb 9, 2015

    @HaloFour

    @HellBrick Even with the enum constraint the problem is that the underlying type could be anything from sbyte to ulong and the IL for the bitwise math would have to be different for each of those types.

    Some of this came up on the CodePlex Roslyn forums when I proposed supporting an enum constraint for C# generics with support for | and &.

  5. mikedn commented on Feb 9, 2015

    @mikedn
    Contributor

    sbyte to ulong and the IL for the bitwise math would have to be different for each of those types

    As I explained before, the bitwise operations themselves are fine. The problem is with conversions that are needed in certain cases. That's something that could probably be fixed in the runtime, at least in the specific case of enums.

  6. terrajobst commented on Jan 5, 2016

    @terrajobst
    Contributor

    @mikedn

    With the current language and runtime capabilities there's no way to implement SetFlag and RemoveFlag efficiently. Even the existing HasFlag has horrible performance compared to the "manual" way of testing flags.

    I agree with this with why I believe we shouldn't add these APIs.

    @weshaggard @KrzysztofCwalina what are your thoughts?

  7. yufeih commented on Jan 5, 2016

    @yufeih
    ContributorAuthor

    I can see how HasFlags is implemented in a really inefficient way. These methods should not be added like that. Maybe some kind of JitIntrinsic from coreclr might help here?
    If the effort is not worth the outcome, I am fine with leaving things as is.

  8. KrzysztofCwalina commented on Jan 5, 2016

    @KrzysztofCwalina
    Member

    @terrajobst, I agree that we don't want to simply add these APIs, but I would put this (efficient flags/bitwise operations) issue on our list of big ticket items that we would like to consider fixing as part of the "modern BCL" push.

  9. HaloFour commented on Jan 5, 2016

    @HaloFour

    It would make a lot more sense to wait until C# supported generic enum constraints:

    dotnet/roslyn#262

  10. KrzysztofCwalina commented on Jan 5, 2016

    @KrzysztofCwalina
    Member

    I am not sure how enum constraint would help. The type system still needs to describe the size of the backing integral type to implement many of these operations efficiently. I think something like making enums extend Enum where T: integral type would be needed.

  11. HaloFour commented on Jan 5, 2016

    @HaloFour

    @KrzysztofCwalina True. Not perfect, but wouldn't an unchecked cast to ulong and then back to the enum type be more efficient than what we have today?

  12. terrajobst commented on Jan 6, 2016

    @terrajobst
    Contributor

    Not sure that would work in all cases either. What if the enum is backed by a double/float? C# doesn't support CLI does.

  13. kornman00 commented on Mar 6, 2016

    @kornman00

    @terrajobst is there online documentation covering that fact (CLI supporting non-integral backing types for enums)? Not finding any obvious results with my Google-fu

  14. mikedn commented on Mar 6, 2016

    @mikedn
    Contributor

    is there online documentation covering that fact (CLI supporting non-integral backing types for enums)? Not finding any obvious results with my Google-fu

    Hmm, didn't notice this comment before. There's no such enum, CLI supports only enums of integral type:

    The symbols of an enum are represented by an underlying integer type: one of { bool, char, int8, unsigned int8, int16, unsigned int16, int32, unsigned int32, int64, unsigned int64, native int, unsigned native int }

    The difference between what CLI supports and what C# supports is { bool, char, native int, native unsigned int }

  15. 13 remaining items

  16. danmoseley commented on Aug 12, 2020

    @danmoseley
    Contributor

    This isn't required to ship 5.0

  17. modified the milestones: 5.0.0, Future on Aug 12, 2020
  18. adamsitnik commented on Dec 9, 2020

    @adamsitnik
    Member

    @danmosemsft Is there any chance we could introduce this API in 6.0? I find myself implementing it in every project I use ;)

  19. danmoseley commented on Dec 9, 2020

    @danmoseley
    Contributor

    @adamsitnik if you are passionate about it your next step would be to get to api-ready-for-review and represent at API review.

  20. zgabi commented on Dec 19, 2020

    @zgabi
    Contributor

    There should be a non-generic version of the SetFlag/WithFlags/RemoveFlags/WithoutFlags, too.

    For example:
    public static object SetFlag(Type enumType, object value, object flag)
    Or with ref parameter.

    Similar to the Parse/TryParse methods: #14083

  21. mburbea commented on Mar 21, 2021

    @mburbea

    I would propose the following api to solve this:

    public class Enum: ValueType
    {
    +public T SetFlag<T>(T flag, bool condition = true) where T:struct,Enum;
    +public T UnsetFlag<T>(T flag) where T:struct,Enum => SetFlag(flag, false);
    }

    Edit: @danmoseley, anything else needed before this api could be ready for review?

    I wrote this as an extension recently while updating a wpf application that bound several checkboxes to a single flagged enum. This made the properties I bound to on my object model nice and symmetric.
    e.g.

            public bool IsStolen
            {
                get => _flags.HasFlag(InventoryFlags.IsFromStolenSource);
                set => _flags = _flags.SetFlag(InventoryFlags.IsFromStolenSource, value);
            }

    Unfortunately the implementation itself was super hideous.

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    internal static T SetFlag<T>(this T @enum, T flag, bool on) where T : struct, Enum
    {
        if (Unsafe.SizeOf<T>() == 1)
        {
            byte x = (byte)((Unsafe.As<T, byte>(ref @enum) & ~Unsafe.As<T, byte>(ref flag))
                | (-Unsafe.As<bool, byte>(ref on) & Unsafe.As<T, byte>(ref flag)));
            return Unsafe.As<byte, T>(ref x);
        }
        else if (Unsafe.SizeOf<T>() == 2)
        {
            var x = (short)((Unsafe.As<T, short>(ref @enum) & ~Unsafe.As<T, short>(ref flag))
                | (-Unsafe.As<bool, byte>(ref on) & Unsafe.As<T, short>(ref flag)));
            return Unsafe.As<short, T>(ref x);
        }
        else if (Unsafe.SizeOf<T>() == 4)
        {
            uint x = (Unsafe.As<T, uint>(ref @enum) & ~Unsafe.As<T, uint>(ref flag))
               | ((uint)-Unsafe.As<bool, byte>(ref on) & Unsafe.As<T, uint>(ref flag));
            return Unsafe.As<uint, T>(ref x);
        }
        else
        {
            ulong x = (Unsafe.As<T, ulong>(ref @enum) & ~Unsafe.As<T, ulong>(ref flag))
               | ((ulong)-(long)Unsafe.As<bool, byte>(ref on) & Unsafe.As<T, ulong>(ref flag));
            return Unsafe.As<ulong, T>(ref x);
        }
    }
  22. hopperpl commented on Nov 18, 2021

    @hopperpl

    What is the state of this now? Before I start yet another round of API suggestions for Enum.HasAnyFlag() et al.

    Enum.HasFlag is now inlined without performance penalty and it makes code look better, imo. And as a bonus in DEBUG it comes with a type check. Set/Unset/Has/HasAny will also avoid endless castings to/from int as the compiler is not smart enough to do it automatically.

    This is 6.5 years old. There should be a decision now if it will be added or dropped.

  23. tannergooding commented on Aug 22, 2022

    @tannergooding
    Member

    @jkotas, any concerns on adding additional APIs to System.Enum here. It sounds like there would be 1-3 APIs and there has been continued interest since the initial proposal 7 years ago.

    The three core scenarios are "set", "clear", and "toggle". Which could be handled via a single API:

    public static TEnum SetFlag<TEnum>(TEnum value, TEnum flag, bool value);

    or a set of APIs:

    public static TEnum ClearFlag<TEnum>(TEnum value, TEnum flag);
    public static TEnum SetFlag<TEnum>(TEnum value, TEnum flag);
    public static TEnum ToggleFlag<TEnum>(TEnum value, TEnum flag);

    names up for debate, as would be whether they are instance or static.

  24. danmoseley commented on Aug 22, 2022

    @danmoseley
    Contributor

    cc @stephentoub here, since as I recall in a previous issue, he argued against providing alternative syntactic sugar to do basic flags operations. Instead we should just make sure that the standard way of writing such things (which is not C# specific) is efficient. I have to say I agree. When I see one of these methods, I would wonder which one to use.

    Apologies for overlooking the ping to me higher up.

  25. stephentoub commented on Aug 22, 2022

    @stephentoub
    Member

    We've closed other related proposals, e.g. #66261. @jkotas has also expressed an opinion similar to mine, e.g. #55455 (comment), and also highlighted that just doing the idiomatic bit operations are guaranteed to be efficient where such named methods aren't, e.g. #55455 (comment).

  26. tannergooding commented on Aug 22, 2022

    @tannergooding
    Member

    Closing as per the comments above.

  27. ghost locked as resolved and limited conversation to collaborators on Sep 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions