Search code examples
c#enumsflags

Elegant way to represent project state in enum


I use a enum for describe different project states:

[Flags]
public enum ProjectStatus
{
   Undefined = 1 << 0,
   Closed = 1 << 1,
   Opened =1 << 2,
   ToMigrate = 1<<3 
}

Now, if I want to go from one state to another, I have to check if this is possible. For this I had the idea to extend my enum as follow:

[Flags]
public enum ProjectStatus
{
   Undefined = 1 << 0,
   Closed = 1 << 1,
   Opened = 1 << 2,
   ToMigrate = 1<<3,
   CanOpen = Opened | ToMigrate,
   CanClose = Opened,
   CanDelete = Closed | ToMigrate 
}

With this solution im able to check a state change:

if ((actualState & CanOpen) == CanOpen)
   {
      // open is allowed.
   }

My only problem is now, that e.g. CanClose and Opened have the same underlying value and CanClose == Opened is true.

So my question is, if someone knows an alternative way to handle this problem in a more elegant way. (maybe with two different enum types?)

thanks in advance!


Solution

  • Use distinct values, do not mess up them together, for example

    public enum ProjectStatus
    {
       Undefined = 1 << 0,
       Closed = 1 << 1,
       Opened = 1 << 2,
       ToMigrate = 1<<3      
    }
    

    And after check if the project can be closed in a function

    public bool CanClose(ProjectStatus status)
    {
        return (status & Opened) == Opened;
    }
    

    Something like this. You should definitely imrove this code, this is just an example.

    In other words, move desicional logic out of enum in a functions. In enum leave only a raw data.