Does anyone know (and perhaps: since when) the -=
operator is supported on enum
values?
I was happily coding away today when I, for some reason, wrote this to exclude a value from a flags enum
:
flags -= FlagsEnum.Value1;
After rereading and evaluating my code, I was surprised that it compiled actually worked.
Writing the statement as
flags = flags - FlagsEnum.Value1
however does not compile.
I couldn't find anything in the documentation and on internet so far. Also, other operators (apart from the bit operators, of course) are not supported: +=
(including a flag) , *=
(intersection in Pascal) don't work.
Is this some syntactic sugar built into the C# compiler? If so, any reason why they chose not to include other operators?
A simple code sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
[Flags]
enum FlagsEnum
{
None = 0,
Value1 = 1,
Value2 = 2,
Value3 = 4
}
class Program
{
static void Main(string[] args)
{
FlagsEnum flags = FlagsEnum.Value1 | FlagsEnum.Value2 | FlagsEnum.Value3;
Console.WriteLine(flags);
flags -= FlagsEnum.Value1;
Console.WriteLine(flags);
flags -= FlagsEnum.Value3;
Console.WriteLine(flags);
flags -= FlagsEnum.Value2;
Console.WriteLine(flags);
Console.ReadLine();
}
}
}
"enum" values should not be used as operands to built-in operators other than [ ], =, ==, != , unary &, and the relational operators <, <=, >, >=
You can use extension methods to add functionality specific to a particular enum type.
Numeric EnumNumeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Iirc, -
is still integer subtraction.
To do exclusion you want:
value = value & ~SomeEnum.Flag;
And inclusion:
value = value | SomeEnum.Flag;
Likewise, to test for a partial match (any bit from Flag):
if((value & SomeEnum.Flag) != 0) {...}
Or a full match (all the bits in Flag):
if((value & SomeEnum.Flag) == SomeEnum.Flag) {...}
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