Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most common C# bitwise operations on enums

People also ask

Is C or C++ more common?

C++ is "doing very well", Tiobe CEO Paul Jansen, says in the company's September 2020 index for the world's most popular programming languages. C++ currently ranks fourth, behind C, Java, and Python.

What is C used for mostly?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Why is C most popular?

The C programming language is so popular because it is known as the mother of all programming languages. This language is widely flexible to use memory management. C is the best option for system level programming language.

Is C the most popular language?

Python is the top programming language in TIOBE and PYPL Index. C closely follow Top-ranked Python in TIOBE. In PYPL, a gap is wider as top-ranked Python has taken a lead of close to 10% from 2nd ranked Java.


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

In .NET 4 you can now write:

flags.HasFlag(FlagsEnum.Bit4)

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);

@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.


.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.


C++ syntax, assuming bit 0 is LSB, assuming flags is unsigned long:

Check if Set:

flags & (1UL << (bit to test# - 1))

Check if not set:

invert test !(flag & (...))

Set:

flag |= (1UL << (bit to set# - 1))

Clear:

flag &= ~(1UL << (bit to clear# - 1))

Toggle:

flag ^= (1UL << (bit to set# - 1))

For the best performance and zero garbage, use this:

using System;
using T = MyNamespace.MyFlags;

namespace MyNamespace
{
    [Flags]
    public enum MyFlags
    {
        None = 0,
        Flag1 = 1,
        Flag2 = 2
    }

    static class MyFlagsEx
    {
        public static bool Has(this T type, T value)
        {
            return (type & value) == value;
        }

        public static bool Is(this T type, T value)
        {
            return type == value;
        }

        public static T Add(this T type, T value)
        {
            return type | value;
        }

        public static T Remove(this T type, T value)
        {
            return type & ~value;
        }
    }
}