tags:

views:

1268

answers:

3

I have a list of error codes I need to reference, kinda like this:

Code / Error Message  
A01 = whatever error  
U01 = another error  
U02 = yet another error type

I get the Code returned to me via a web service call and I need to display or get the readable error. So I need a function when passed a Code that returns the readable description. I was just going to do a select case but thought their might be a better way. What is the best way / most effieient way to do this?

A: 

Statically initialized Hashmap?

Rohit
That would be my guess. The only reason I am not voting up now is because you lack an explanation. I would assume somebody asking this question would not know what a hashmap is ;)
nlaq
+7  A: 

Use a Dictionary, (in C#, but the concept and classes are the same):

// Initialize this once, and store it in the ASP.NET Cache.
Dictionary<String,String> errorCodes = new Dictionary<String,String>();

errorCodes.Add("A01", "Whatever Error");
errorCodes.Add("U01", "Another Error");


// And to get your error code:

string ErrCode = errorCodes[ErrorCodeFromWS];
FlySwat
You downvoted us! Why? Our answers were not wrong. A hashtable (dictionary, hashmap) should be well-known or at least easy to look up for any programmer. Besides, he didn't say whether he's using C#.
Cybis
Note that with C# 3.0 and collection initializers the dictionary initialization could be a lot more readable. (Admittedly it's a VB.NET question - just thinking aloud.) It's also worth considering putting the mapping in a file, so it can be updated without rebuilding.
Jon Skeet
He's not. Apparently he is using VB.net. I would agree that your answers should not be downvoted; but should not necessarily be up voted unless you provided more details or practical examples. That is just my opinion though.
nlaq
thanks - exactly what I needed.
Slee
A: 

You would use a dictionary. A dictionary uses a hashmap internally for performance, so it is good in that regard. Also, because you want this to go as quickly as possible by the sounds of it, I would statically initialize it in its own class instead of, for example, in an XML file or slimier. You would probably want something like:

public static class ErrorCodes
{
    private static Dictonary<string, string> s_codes = new Dicontary<string, string>();
    static ErrorCodes()
    {
         s_codes["code"] = "Description";
         s_codes["code2"] = "Description2";
    }

    public static string GetDesc(string code)
    {
         return s_codes[code];
    }
}

That way, if you wanted to move the back end to a file instead of being static, then you could.

nlaq