Building up query strings is quite a common task in web development but there is currently no utility class in .Net that neatly facilitates this. So I thought I’d have a go at creating one that nicely encapsulates the build process and makes use of Generic Collections. And here is what I came up with!
public class QueryString
{
private Dictionary _Params = new Dictionary();
public overide ToString()
{
List returnParams = new List();
foreach (KeyValuePair param in _Params)
{
returnParams.Add(String.Format("{0}={1}", param.Key, param.Value));
}
return "?" + String.Join("&", returnParams.ToArray());
}
public void Add(string key, string value)
{
_Params.Add(key, HttpUtility.UrlEncode(value));
}
}
This can be used like so
QueryString query = new QueryString();
query.Add("param1", "value1");
query.Add("param2", "value2");
return query.ToString();
Filed under: Code




