Sunday, September 2, 2012

Using enums as constants

The other day I found myself having to add a value in to a dictionary with a number of constant keys. I started out with this:

//populating method:
dictionary["constant1"] = value1;
dicitonary["constant2"] = value2;
...
//consuming method:
value1 = dictionary["constant1"];
value2 = dictionary["constant2"];

Then I felt bad. I really should have them in constants. So,

private const string constant1key = "constant1key";
private const string constant2key = "constant2key";

And I felt better. But there were a number of these constants, and if someone added one later and inadvertently used an existing string value, it would be a nasty bug. So I ended up with this:

public class MyClass {
  private enum Keys
  {
    constant1,
    constant2
  }
  ...
  //populating method:
  dictionary1[Keys.constant1.ToString()] = value1;
  dictionary1[Keys.constant2.ToString()] = value2;
  ...
  //consuming method:
  value1 = dictionary1[Keys.constants1.ToString()];
  value2 = dictionary1[Keys.constants2.ToString()];
}

The few extra keystrokes typing "ToString()" are justified by eliminating the possibility of accidentally duplicating a name. It's always a good thing when the compiler can prevent you from making a mistake. And I like the fact that the enum is scoped inside the class, keeping the external namespace clean. An important point is that while an enum can be cast to an int, the ToString method gives the name of the enum, in this case, "constant1".

2 comments:

  1. Nice tip. I haven't really thought of using .ToString() on enums.

    ReplyDelete
  2. who is this Derek guy? I bet he's a decent developer...hmmm

    ReplyDelete