Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple choice enum

Tags:

c#

enums

I am lately starting a project and I have a question.

Let's say I am dealing with a class Person, and a person can have one(or more) deseases he is encountering. so I have created an enum :

 public enum diseases{headache,throat,bruise,gunshot,none}; // enum containing all the diseases
 public diseases disease; 

And further in code I set a certain disease to that person and it works fine.

Thing is, there might be a point in my project where a person might have 2 diseases. So there are my questions:

  1. Is using enum the best option here? I want my code to be organized and understood and that's a main reason for using enums.
  2. If using enum is a good option, I have managed to combine this enum with bit-flags(using [System.Flags]) so when time comes I can check for a disease that contains two different values from the enum. is this a good approach?
  3. If using enum is a good option, should I just create a second property from diseases (just like I created disease) and save all the trouble from using bit-flags?

Thanks in advance for any light on that matter, couldn't figure what was the best approach here.

like image 700
Oranges Avatar asked May 21 '26 02:05

Oranges


2 Answers

A good option would to make a List<diseases> to hold for a single person.

public class Person
{
    public string Name { get; set; }
    public List<diseases> Diseases { get; set; }

    public Person(string name)
    {
        this.Name = name;
        Diseases = new List<diseases>();
    }
}

This way you can enumerate over all the values relatively easily without having to worry about flags.

For example:

var bob = new Person("bob");
bob.Diseases.Add(diseases.gunshot);

var hasHeadache = bob.Diseases.Any(x => x == diseases.headache);
like image 194
gunr2171 Avatar answered May 22 '26 16:05

gunr2171


An enum is a plausible (yet a bit simplistic) way to represent one disease.

If someone may have N diseases, then just use a container of objects of that type, such as a list. But you need to choose the right container. A list of diseases may be, for example: { headache, throat, headache, throat, gunshot }. Lists allow duplicates. Whay you may actually need is a set of diseases. A set is a structure which does not allow duplicates.

The choice of how you represent one disease and the fact that a person may have N diseases, so that you need a person to have a container of diseases, are two totally independent facts.

like image 40
Daniel Daranas Avatar answered May 22 '26 16:05

Daniel Daranas