Most common C# bitwise operations on enums

c# enum
c# bitwise operators
c# enum flags multiple values
enum class c#
c# enum bitwise shift
combine enums c#
c# enum flags all
bit flags c#

For the life of me, I can't remember how to set, delete, toggle or test a bit in a bitfield. Either I'm unsure or I mix them up because I rarely need these. So a "bit-cheat-sheet" would be nice to have.

For example:

flags = flags | FlagsEnum.Bit4;  // Set bit 4.

or

if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way?

Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum?

I did some more work on these extensions - You can find the code here

I wrote some extension methods that extend System.Enum that I use often... I'm not claiming that they are bulletproof, but they have helped... Comments removed...

namespace Enum.Extensions {

    public static class EnumerationExtensions {

        public static bool Has<T>(this System.Enum type, T value) {
            try {
                return (((int)(object)type & (int)(object)value) == (int)(object)value);
            } 
            catch {
                return false;
            }
        }

        public static bool Is<T>(this System.Enum type, T value) {
            try {
                return (int)(object)type == (int)(object)value;
            }
            catch {
                return false;
            }    
        }


        public static T Add<T>(this System.Enum type, T value) {
            try {
                return (T)(object)(((int)(object)type | (int)(object)value));
            }
            catch(Exception ex) {
                throw new ArgumentException(
                    string.Format(
                        "Could not append value from enumerated type '{0}'.",
                        typeof(T).Name
                        ), ex);
            }    
        }


        public static T Remove<T>(this System.Enum type, T value) {
            try {
                return (T)(object)(((int)(object)type & ~(int)(object)value));
            }
            catch (Exception ex) {
                throw new ArgumentException(
                    string.Format(
                        "Could not remove value from enumerated type '{0}'.",
                        typeof(T).Name
                        ), ex);
            }  
        }

    }
}

Then they are used like the following

SomeType value = SomeType.Grapes;
bool isGrapes = value.Is(SomeType.Grapes); //true
bool hasGrapes = value.Has(SomeType.Grapes); //true

value = value.Add(SomeType.Oranges);
value = value.Add(SomeType.Apples);
value = value.Remove(SomeType.Grapes);

bool hasOranges = value.Has(SomeType.Oranges); //true
bool isApples = value.Is(SomeType.Apples); //false
bool hasGrapes = value.Has(SomeType.Grapes); //false

Enum, Flags and bitwise operators, Learn how to master Enum, Flags and bitwise operators in C#. The most naive way of implementing this is simply by using constants: C#. The following operators perform bitwise or shift operations with operands of the integral numeric types or the char type: Unary ~ (bitwise complement) operator Binary << (left shift) and >> (right shift) shift operators Binary & (logical AND), | (logical OR), and ^ (logical exclusive OR) operators

In .NET 4 you can now write:

flags.HasFlag(FlagsEnum.Bit4)

Enumerations, bitwise operators and flags, The most common way to use an enumeration is to use its values separately. There are however times when we want to use a combination of the� Luckily, C# has a construct called enum (for enumeration) which has been specifically designed for these situations: C# // Outside your class public enum AttackType { None, Melee, Fire, Ice, Poison } // Inside your class public AttackType attackType = AttackType.None;

The idiom is to use the bitwise or-equal operator to set bits:

flags |= 0x04;

To clear a bit, the idiom is to use bitwise and with negation:

flags &= ~0x04;

Sometimes you have an offset that identifies your bit, and then the idiom is to use these combined with left-shift:

flags |= 1 << offset;
flags &= ~(1 << offset);

Enumeration types, To define an enumeration type, use the enum keyword and specify the names of enum members: C# Then, you can use the bitwise logical operators | or & to combine For more information and examples, see the System. values - Most common C# bitwise operations on enums enum operator c# (6) .NET's built-in flag enum operations are unfortunately quite limited.

@Drew

Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

[Flags]
public enum TestFlags
{
    One = 1,
    Two = 2,
    Three = 4,
    Four = 8,
    Five = 16,
    Six = 32,
    Seven = 64,
    Eight = 128,
    Nine = 256,
    Ten = 512
}


class Program
{
    static void Main(string[] args)
    {
        TestFlags f = TestFlags.Five; /* or any other enum */
        bool result = false;

        Stopwatch s = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
        {
            result |= f.HasFlag(TestFlags.Three);
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*

        s.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            result |= (f & TestFlags.Three) != 0;
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        

        Console.ReadLine();
    }
}

Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

FlagsAttribute Class (System), C# Copy. [System.AttributeUsage(System.AttributeTargets.Enum, Inherited=false) ] public class FlagsAttribute : Attribute use bitwise logical and equality operators to determine whether one or more bit fields are set in an enumeration value. Consider creating an enumerated constant for commonly used flag combinations� Flag enums are designed to support bitwise operations on the enum values. A common example of the flags enum is a list of options. ✔️ DO use an enum to strongly type parameters, properties, and return values that represent sets of values. ✔️ DO favor using an enum instead of static constants.

.NET's built-in flag enum operations are unfortunately quite limited. Most of the time users are left with figuring out the bitwise operation logic.

In .NET 4, the method HasFlag was added to Enum which helps simplify user's code but unfortunately there are many problems with it.

  1. HasFlag is not type-safe as it accepts any type of enum value argument, not just the given enum type.
  2. HasFlag is ambiguous as to whether it checks if the value has all or any of the flags provided by the enum value argument. It's all by the way.
  3. HasFlag is rather slow as it requires boxing which causes allocations and thus more garbage collections.

Due in part to .NET's limited support for flag enums I wrote the OSS library Enums.NET which addresses each of these issues and makes dealing with flag enums much easier.

Below are some of the operations it provides along with their equivalent implementations using just the .NET framework.

Combine Flags

.NET             flags | otherFlags

Enums.NET flags.CombineFlags(otherFlags)


Remove Flags

.NET             flags & ~otherFlags

Enums.NET flags.RemoveFlags(otherFlags)


Common Flags

.NET             flags & otherFlags

Enums.NET flags.CommonFlags(otherFlags)


Toggle Flags

.NET             flags ^ otherFlags

Enums.NET flags.ToggleFlags(otherFlags)


Has All Flags

.NET             (flags & otherFlags) == otherFlags or flags.HasFlag(otherFlags)

Enums.NET flags.HasAllFlags(otherFlags)


Has Any Flags

.NET             (flags & otherFlags) != 0

Enums.NET flags.HasAnyFlags(otherFlags)


Get Flags

.NET

Enumerable.Range(0, 64)
  .Where(bit => ((flags.GetTypeCode() == TypeCode.UInt64 ? (long)(ulong)flags : Convert.ToInt64(flags)) & (1L << bit)) != 0)
  .Select(bit => Enum.ToObject(flags.GetType(), 1L << bit))`

Enums.NET flags.GetFlags()


I'm trying to get these improvements incorporated into .NET Core and maybe eventually the full .NET Framework. You can check out my proposal here.

Using enum types as bit flags in C#, Sign up now and get 15% discount with the code yanprs15! Tweet You use the FlagsAttribute attribute to create an enum type as bit flags which you can then interact with using the AND (&), OR (|), NOT (~) and XOR (^) bitwise operations: In the meantime, here are a few of my most popular blog posts. I have a target persisted value of one enum, and I have the user's settings of that same enum. I need to compare the two to see if there is a single match of one or more enum bits set. Bonus: I would love to use bitwise operators here to shortcut the linq query (cause I replicate this 5 or 6 times throughout different properties).

C# enum Flags Attribute Examples, An enum type with the [Flags] attribute can have multiple constant values assigned to it. With Flags Operators: We use bitwise operators, like OR and AND, with enum flags. Enum flags represent more complex constants and combinations. A fellow developer suggested we store a selection of days of the week as 7-character string of 1’s and 0’s, i.e. “1000100” for Monday and Friday. I preferred (and strongly suggested) a solution with a Flags enum and bitwise operations, I think it's a cleaner way of doing this, and it should be easier to understand for other developers.

The Beginner's Guide to Using Enum Flags, Once I was roaming the Visual C++ forum (again), I had to face the fact that bitwise operations, and binary in general, are rarely in beginner's common sense . C# - Bitwise Operators - The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −

Store user options using enumeration, bitwise operators, and EF Core, There are several types of notifications supported by the application Yet another approach is to use C# enumerations, bitwise operators, and� Enumerated types in the C# programming language preserve most of the "small integer" semantics of C's enums. Some arithmetic operations are not defined for enums, but an enum value can be explicitly converted to an integer and back again, and an enum variable can have values that were not declared by the enum definition. For example, given

Comments
  • This has been answered before here
  • too bad that link doesn't appear in the question hints for this topic.
  • That question is tagged for c/c++, though, so someone searching for info about C# would probably not look there even though the syntax appears to be the same.
  • I'm not aware of a less verbose way to do the bit test
  • @Andy, there's an API for the bit test in .NET 4 now.
  • I also found this useful - Any ideas how I can modify it so it works on any underlying type?
  • These extensions just made my day, my week, my month, and quite possibly my year.
  • Thank you! Everybody: be sure to check out the update Hugoware has linked to.
  • A very nice set of extensions. It's a shame they require boxing, though I can't think of an alternative that doesn't use boxing and is this succinct. Even the new HasFlag method on Enum requires boxing.
  • @Drew: See code.google.com/p/unconstrained-melody for a way of avoiding boxing :)
  • +1 for pointing that out, although FlagsEnum is an ugly name. :)
  • @Jim, perhaps. It's just a sample name, as used in the original question, so you're free to change it in your code.