C# – Is It Better to Use String or Enum as a Key?

cenumobject-oriented

Example 1 (used at the moment)

If (BodyPart["Right Leg"].BodyStatusEffects["Active"].Active)
{
    BodyPart["Right Leg"].BodyStatusImpacts["Poisoned"].Active = false;

    BodyPart["Torso"].BodyStatusImpacts["Poisoned"] = 
        BodyPart["Right Leg"].BodyStatusImpacts["Poisoned"];

    BodyPart["Right Foot"].BodyStatusImpacts["Poisoned"] = 
        BodyPart["Right Leg"].BodyStatusImpacts["Poisoned"];
}

Example 2

BodyPart.[BodyParts.RightLegs].BodyStatusImpacts["Poisoned"].Active = false;

Which of these two examples is the preferred method? Is there a 3rd way that is even better?

Best Answer

I would generally recommend using enums in this situation. Reasons:

  • It defines very clearly what is allowed and what is not allowed in the structures that are keyed with them, if you define the enum type as the key.
  • Your IDE will probably give you auto-complete functionality which is easier and faster than typing an open-quote, typing a string, then a close-quote.
  • If you ever need to generate a list of all keys used in your program, it is much easier to iterate over an enum than to search for all references to the underlying data structure and then find all the different string keys you used.
  • It's relatively easy to type the wrong string as a key and then waste time trying to figure out why your program won't work. Can't make that same mistake with an enum.
  • If you ever need to change an enum value, your IDE will probably let you refactor it very easily. With strings as keys, you'll be doing a lot of find-and-replace on the text and hope you got it all.

One problem with enums is that you can't add new values to an enum at runtime (at least I don't know of any way to), so if your program will need to be able to create entirely new keys based on user input at runtime, enums can't help you with that. But you could key your data structure with "soft" enums (the string values of the enums) and user-entered strings to get a sort of hybrid solution.

Related Topic