Today, I ran into a strange little issue regarding the System.Uri class that took me too long to figure out. The Uri class has a property called Query that, according to the documentation, returns everything from the "?" to the end of the URI.

Consider this unescaped URI:

string url = "http://www.google.com/search?q=httpcompression c# asp.net";

string query = new Uri(url).Query;

The Uri.Query on that URI returns q=httpcompression c. As you can see, it breaks when it encounters a "#" character, so it doesn’t return everything from the "?" to the end. If the URI was escaped or UrlEncoded, there would have been no problem because the "#" character would be encoded into "%23". The problem is, that in this particular case I had to deal with unescaped URIs. 

So to make the above code work properly, the simplest way was to do exactly what the documentation for the URI.Query says: Return everything from the question mark to the end of the URI. That lead to the following helper method.

string url = "http://www.google.com/search?q=httpcompression c# asp.net";

string query = ExtractQuery(url);

 

public static string ExtractQuery(string url)

{

  if (string.IsNullOrEmpty(url))

    return string.Empty;

 

  int index = url.IndexOf("?") + 1;

  if (index == 0)

    return string.Empty;

 

  return url.Substring(index);

}

>

>

It’s not bad or ugly in any way, but it is annoying and also frustrating that the documentation isn’t correct either.

…Or at least a class I didn’t know existed, but let’s see if I’m right or not. The class resides in the System.Web.UI namespace and is used various places in ASP.NET. Among those places are the inner workings of the ViewState. The reason you (might) don’t know the class could be because of its not so strongly typed nature. In other words, if you want to use the class you have to do a lot of boxing and casting.

As you haven’t already guessed, I’m talking about the Triplet class. I’ve thought about how to use the class instead of creating my own type-safe little structures, and I came up with nothing. I don’t know what to do with the class.

Here is how you could use it

Triplet triplet = new Triplet();

triplet.First = "string";

triplet.Second = 34;

triplet.Third = DateTime.Now;

If you have any good ideas to how you would use this class, please let me know. My own imagination is limited when it comes to the Triplet class.

>