In an ASP.NET page, if you call Request.QueryString.ToString(), you’ll get a nicely formatted query string back, like this:

my=query&string=value&foo=bar

“That’s nice,” I thought. “I wonder how they implemented it. I’ll fire up Reflector and take a look.”

However, when you look at the declaration of QueryString in HttpRequest, you’ll see that it is of type NameValueCollection, a class that has no ToString() override; at first glance, it looks like you’d simply be calling System.Object.ToString().

Obviously, this is not what is happening, so to find out how the query string is being generated, I had to dig just a little bit deeper. Fortunately, VS2008 lets you step into the framework.

When you step in you’ll see that HttpRequest.QueryString is indeed defined to be of type NameValueCollection, but when it actually gets instantiated, it is initialized to be of type HttpValueCollection, an internal class that derives from NameValueCollection.

HttpValueCollection has a ToString() override that does the dirty work of constructing the nice query string that you see at the top of this post.

I’m so glad that Microsoft decided to allow us to step into the framework source code. Otherwise, I probably would have spent a good hour trying to track down the magical NameValueCollection.ToString() call.