Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums and subtraction operator

Tags:

c#

enums

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();
        }
    }
}
like image 620
Willem van Rumpt Avatar asked Mar 12 '11 18:03

Willem van Rumpt


People also ask

What operators can have enum operands?

"enum" values should not be used as operands to built-in operators other than [ ], =, ==, != , unary &, and the relational operators <, <=, >, >=

Can you add methods to enums?

You can use extension methods to add functionality specific to a particular enum type.

Can enums have numbers?

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.

Can two enums have the same value?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.


1 Answers

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) {...}
like image 136
Marc Gravell Avatar answered Sep 28 '22 00:09

Marc Gravell