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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With