2
\$\begingroup\$

I have the following code:

    public string GetRefStat(string pk) {
        return RefStat[pk.Substring(2, 2)];
    }
    private readonly Dictionary<String, int> RefStat =
    new Dictionary<string, int> 
    {
        {"00", REF.MenuType,       } // Menu
        {"01", REF.ReferenceStatus,} // Article
        {"02", REF.ReferenceStatus,} // Favorites List
        {"03", REF.ReferenceStatus,} // Content Block
        {"06", REF.ReferenceStatus } // Topic
    };

GetRefStat and the dictionary are always used together.

Is there a way I could simplify and combine these? I was wondering if I could put the information in a static class and then have a get method that returned the information I needed.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Your code won't compile. The dictionary contains ints, but the method returns strings. Also, some commas in your definition of the dictionary are misplaced (they should outside the braces, not inside). \$\endgroup\$ – svick Sep 14 '12 at 14:10
  • \$\begingroup\$ Does REF.ReferenceStatus have to be a integer or could it be an enumeration instead? If it could be an enumeration you could do something with attributes and enum parsing to get what you want? \$\endgroup\$ – dreza Sep 14 '12 at 20:06
4
\$\begingroup\$

Your code is short, readable and efficient, so I don't think it needs much improvement. And I don't think adding a static class would give you anything (although changing the field and the method to static could make sense).

Another way to write your code would be to use switch, but I'm not sure whether it's more readable (although it could be slightly more efficient):

public string GetRefStat(string pk)
{
    switch (pk.Substring(2, 2))
    {
    case "00":
        return REF.MenuType;
    case "01":
    case "02":
    case "03":
    case "06":
        return REF.ReferenceStatus;
    default:
        throw new InvalidOperationException();
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Although people say to stay away from switches where you can, I actually think I prefer this given that so much of the cases use the same REF. It also lets you control the exception thrown with even a possible explicit message. \$\endgroup\$ – dreza Sep 14 '12 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.