Extension method for adding value to bit field (flags enum)

Ronnie Overby picture Ronnie Overby · Apr 26, 2011 · Viewed 16.5k times · Source

Instead of doing this to add a value to flags enum variable:

MyFlags flags = MyFlags.Pepsi;
flags = flags | MyFlags.Coke;

I'd like to create an extension method to make this possible:

MyFlags flags = MyFlags.Pepsi;
flags.Add(MyFlags.Coke);

Possible? How do you do it?

Answer

Matt Greer picture Matt Greer · Apr 26, 2011

Not in any useful way. Enums are value types, so when making an extension method a copy of the enum will get passed in. This means you need to return it in order to make use of it

    public static class FlagExtensions
    {
        public static MyFlags Add(this MyFlags me, MyFlags toAdd)
        {
             return me | toAdd;
        }
    }

    flags = flags.Add(MyFlags.Coke); // not gaining much here

And the other problem is you can't make this generic in any meaningful way. You'd have to create one extension method per enum type.

EDIT:

You can pull off a decent approximation by reversing the roles of the enums:

public static class FlagsExtensions
{
    public static void AddTo(this MyFlags add, ref MyFlags addTo)
    {
         addTo = addTo | add;
    }
}


MyFlags.Coke.AddTo(ref flags);