0

I have inherited some code that I need to maintain with a server and client. Certain settings are currently passed on to the client via a set of flags of an in-house binary protocol. e.g.,

if (object.has.someAttribEnum == SYS_ON)
  settingsFlag = settingsFlag | 2;
...
...
if(foo.has.someAttribEnum == DISP_ON)
  settingsFlag = settingsFlag | 4398046511104;

These settings are getting quite massive, since the flag is UInt64, so we are at 2^45. And also this function is betting quite huge. It is easy for developers to make mistakes such as using a value not a power of two, breaking the entire settings flag received by the client.

The best solution is probably to be sending on a serialized object over the binary protocol? Due to some implementation and time constraints, this might not be immediately possible.

What could I do to improve the readability and manageability of this? I even started thinking of using shifts inline instead of the values i.e.,

if(foo.has.someAttribEnum == DISP_ON)
  settingsFlag = settingsFlag | (1 << 42);

I appreciated any thoughts on this.

Vort3x
  • 1,778
  • 2
  • 20
  • 37

1 Answers1

4

You could use a [Flags] enum. It allows you to easily define an enum with with different options specified as different values (typically powers of 2) and supports operations for checking if an option is set in a given enum value;

Example:

[Flags]
public enum MySettings : ulong
{
    SYS_ON = 1 << 1,
    DISP_ON = 1 << 42,
}

if (settings.HasFlag(MySettings.SYS_ON))
{
    //do something
}

You can also create/set settings like:

MySettings settings = MySettings.SYS_ON | MySettings.DISP_ON
usr
  • 168,620
  • 35
  • 240
  • 369
mclaassen
  • 5,018
  • 4
  • 30
  • 52
  • I initally thought that you couldn't use longer than Int32, but after reading your answer and the comments above,I tested and ulong works just fine! This is exactly the solution for me for now. Thanks! – Vort3x Jul 22 '14 at 15:45