Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of using a flags enum?

Tags:

c#

bit-fields

I'm receiving several bit fields from hardware.

My code was originally:

public readonly byte LowByte;

public bool Timer { get { return (LowByte & 1) == 1; } }

Then I remembered the flags enum and am considering changing it to:

[Flags]
public enum LowByteReasonValues : byte
{
    Timer = 1,
    DistanceTravelledExceeded = 2,
    Polled = 4,
    GeofenceEvent = 8,
    PanicSwitchActivated = 16,
    ExternalInputEvent = 32,
    JourneyStart = 64,
    JourneyStop = 128
}

public readonly LowByteReasonValues LowByte;

public bool Timer { get { return (LowByte & LowByteReasonValues.Timer) == LowByteReasonValues.Timer; } }

and so on.

Which is best practice and what if any are the pros and cons of each approach?

EDIT: I'm interested to know if there are any practical differences between the two approaches, particularly in regards to performance. I'm not wishing to solicit opinion on coding styles (unless it comes from Microsoft guidelines) as that would see the question closed as unconstructive. Thanks.

like image 237
Stephen Kennedy Avatar asked Oct 26 '11 17:10

Stephen Kennedy


1 Answers

The later is best practice since it makes your code more readable

like image 167
Loman Avatar answered Sep 20 '22 02:09

Loman