0

How can I associate 2 values into a single enum type value in a c# application? For example, I have a enum type like this:

public enum person 
{ 
    soccerPlayer, 
    tennisPlayer, 
    athlete, 
    coach
}

A soccer player and a tennis player are athletes, but a coach is not an athlete.

If I instance a person, like this:

person p = person.soccerPlayer;

How do I do this test?

if (p == person.athlete)
1
  • 5
    You should be using classes. Commented Mar 10, 2013 at 1:35

1 Answer 1

2

In this particular case you would be better served by having a function check to see if the enum value is an athlete

static bool IsAthlete(person p) { 
  switch (p) { 
    case person.soccerPlayer:
    case person.tennisPlayer:
    case person.athlete:
      return true;
    default:
      return false;
  }
}

Overall though I don't believe an enum type serves you well here. An enum is typically used to represent mutually exclusive values (can be A or B but not both) or for bit flag situations. You could manipulate bit flags to work here but i feel like it isn't the best approach.

This is the type of situation which seems more suitable a full fledged type.

class Person { 
  public bool IsAthlete { get; private set; } 
  public bool IsSoccerPlayer { get; private set; } 
  public bool IsTennisPlayer { get; private set; }

  public static readonly TennisPlayer = new Person { 
    IsTennisPlayer = true, 
    IsAthelete = true
  }

  public static readonly SoccerPlayer = new Person { 
    IsSoccerPlayer = true, 
    IsAthelete = true
  }      
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.