Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 358
Ronnie Overby Avatar asked Apr 26 '11 16:04

Ronnie Overby


People also ask

What is a flag enum?

Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.

What is the role of flag attribute in enum?

The [Flag] attribute is used when Enum represents a collection of multiple possible values rather than a single value. All the possible combination of values will come. The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value.

Can C# enums have methods?

C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.


1 Answers

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);
like image 180
Matt Greer Avatar answered Oct 05 '22 23:10

Matt Greer