I have the following as an example:
public enum HttpRequestHeader
{
Accept,
AcceptCharset
}
public static class HTTP
{
public static Hashtable HttpRequestHeaderString
{
get
{
Hashtable returnHashtable = new Hashtable();
returnHashtable.Add(HttpRequestHeader.Accept,"Accept");
returnHashtable.Add(HttpRequestHeader.AcceptCharset,"Accept-Charset");
return returnHashtable;
}
}
}
I will be accessing :
string HttpRequestHeaderString
= HTTP.HttpRequestHeaderStrings[HttpRequestHeader.Accept]
many times. As this is a static HashTable, is there a better way of providing the same functionality more efficiently?
I understand that I can implement this particular solution using a different type of collection, but if I want to use the HashTable – what options are there for me?
Many thanks in advance SO!
Do you want callers to be able to mutate the dictionary? If so, having a static one sounds like a very odd idea. If not, you really only need to be able to response to requests for Accept and AcceptCharset, which I’d probably do in a simple switch statement.
You say you really want to be use a Hashtable – why? What’s the bigger picture here?
Exposing mutable data structures statically is almost always a bad idea. If you want a helper to build a hashtable with some initial values, then I’d make it a method rather than a property. If you don’t need mutation, I’d write a method to fetch the value for a specific
HttpRequestHeaderrather than exposing a collection. For example:Another option would be to have a Java-like enum of headers:
You’d need to do checks against
null, but that would be the only invalid value of RequestHeader that you could get. (Enums aren’t range-checked, so someone could easily write((HttpRequestHeader)-1)in your current code… in other words, it doesn’t fix argument validation anyway.)EDIT: In response to the comment, if you’re using C# 3 and want eager initialization (to make life easier) you could write: