Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for marking an enum with the [Flags] attribute?

We recently ported an old C# app from Visual Studio 2003 to Visual Studio 2010.

In searching for things to clean up in the code, I ran Resharper on it, and it tells me (oodles of times), "Bitwise operation on enum which is not marked by [Flags] attribute"

e.g., here is a bit of code that it "flags" (no pun intended) with that message:

~DuckbillConverter()
{
    //stop running thread
    if((this.Status & ConvertStatus.Running) == ConvertStatus.Running)
        this.Stop();
}

I assume that this code is working as is; so what would be the benefit (or, even more importantly, any possible side effects) of decorating ConvertStatus.Running with the [Flags] attribute, as R# recommends?

UPDATE

Answer to Jon Skeet:

public enum ConvertStatus
{
    /// <summary>
    /// The thread is not running, there are no manual conversions or purges and no errors have occurred.
    /// </summary>
    Stopped = 0x0,
    /// <summary>
    /// The thread is running and will automatically convert all sites for both file types.
    /// </summary>
    Running = 0x1,
    /// <summary>
    /// A data conversion is currently taking place.
    /// </summary>
    Converting = 0x2,
    /// <summary>
    /// A data purge is currently taking place.
    /// </summary>
    Purging = 0x4,
    /// <summary>
    /// An error has occurred.  Use the LastError property to view the error message.
    /// </summary>
    Error = 0x8
}
like image 336
B. Clay Shannon-B. Crow Raven Avatar asked Sep 23 '13 16:09

B. Clay Shannon-B. Crow Raven


2 Answers

Resharper isn't recommending that ConvertStatus.Running receive an attribute, but the entire ConvertStatus enum.

From MSDN, FlagsAttribute is described as:

Indicates that an enumeration can be treated as a bit field; that is, a set of flags.

Since you are using bitwise operations on an enum that isn't indicated to actually be usable as a bit field, R# is warning you that your code may have unintended effects at run time. Using the [Flags] attribute itself doesn't guarantee that the implementation of the enum is actually consistent with the values expected for a bit field, but it does create a contract that the outside world should expect it to be.

like image 165
Preston Guillot Avatar answered Nov 01 '22 23:11

Preston Guillot


It tells the client of the enum that it is indeed Flags. Also you can see Microsoft's example in how it modifies ToString().

like image 20
Yuriy Faktorovich Avatar answered Nov 02 '22 01:11

Yuriy Faktorovich