Stephen Sulzberger’s Blog

May 26, 2008

Use C# ?? null coalescing operator for parsing request query string parameters

Filed under: .net,asp.net,C#,Web development — Stephen @ 7:16 pm

I’m a big fan of succinct code, especially when it comes to satisfying requirements that are ultimately trivial but redundant. That being said, I think the following is the best way to parse query string parameters:

    string sParam = "t"; 
    string sResult = string.Empty; 

    sResult = (Request.QueryString[sParam] ?? "").Trim();

    if (sResult != "")
    {
      // Do something
    }

If the request string param is null, the string returns “”. If the request string param has a value, we snag it and Trim() to ensure that we get what we want and nothing else (this is important, especially since users can toy with the param values and send values with unexpected extra spaces). The idea here is to encapsulate as many “checks” into a simple, quick parse to ensure that you don’t have to back track and validate anything (insofar as handling null or empty data). Notice, also, that I use the Trim() method outside of the “coalescing” routine – this is because if the Request.QueryString[] call returned null, Trim() would throw an object reference exception.

Some other methods you might use for accomplishing the same thing:

Example 1

      string sParam = "t";
      string sResult = string.Empty;
      
      if ((Request.QueryString[sParam] != null) && (Request.QueryString[sParam].Trim() != ""))
      {
        sResult = Request.QueryString[sParam].Trim();
      }

      if (sResult != "")
      {
        // Do something
      }

Example 2

      string sParam = "t";
      string sResult = string.Empty;      
      
      sResult = (null != Request.QueryString[sParam]) ? Request.QueryString[sParam].Trim() : "";

      if (sResult != "")
      {
        // Do something
      }

Example #1 and #2 will each give the same end result and functionality as the null coalescing approach sketched above, but at any rate they contain a lot of redundancy. The null coalescer is the easiest approach of the proffered bunch, I think. 

For more information on the C# null coalescing operator and some other interesting uses (e.g. using it with LINQ), check out: http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx

Create a free website or blog at WordPress.com.