10
if(Page.Request.QueryString["ParamName"] != null)
  if(Page.Request.QueryString["ParamName"] == expectedResult)
    //Do something spectacular

The above seems cludgey. Is there a more elegant/compact way of checking if a query string parameter is not null and if so - retrieving the value of it?

3 Answers3

10

I thought first of offering

if ((Page.Request.QueryString["ParamName"] ?? "") == expectedResult) {

but quickly realized that with strings, comparing some string with null is fine, and will produce false, so really just using this will work:

if(Page.Request.QueryString["ParamName"] == expectedResult)
    //Do something spectacular
7

You can use String.IsNullOrEmpty

String.IsNullOrEmpty(Page.Request.QueryString["ParamName"]);

Or

var parm = Page.Request.QueryString["ParamName"] ?? "";
if(parm == expectedResult)
{

}
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
  • What about the value of ParamName? You've only tackled the first line of my code (effectively nonetheless, I should really be using IsNullOrEmpty - so +1). –  Jun 29 '12 at 10:54
2

I personally would go with a simple set of extension methods, something like this:

public static class RequestExtensions
{
    public static string QueryStringValue(this HttpRequest request, string parameter)
    {
        return !string.IsNullOrEmpty(request.QueryString[parameter]) ? request.QueryString[parameter] : string.Empty;
    }

    public static bool QueryStringValueMatchesExpected(this HttpRequest request, string parameter, string expected)
    {
        return !string.IsNullOrEmpty(request.QueryString[parameter]) && request.QueryString[parameter].Equals(expected, StringComparison.OrdinalIgnoreCase);
    }
}

and a sample usage

string value = Page.Request.QueryStringValue("SomeParam");
bool match = Page.Request.QueryStringValueMatchesExpected("SomeParam", "somevaue");
Kane
  • 16,471
  • 11
  • 61
  • 86
  • Is better to write code that can be fully, fast and easy understand what is done with the first look by other developers that may come to continue your code. Also if you see how much code is product by the lines you write you realize that you make slow code. A simple `==` is done the work. – Aristos Jun 29 '12 at 11:15
  • 1
    Happy to accept criticism but can you explain how the code is considered to be 'slow'? – Kane Jun 29 '12 at 11:27
  • Because I am also accept criticism, I take back the slow code, I check it and the compile create what I see, not extra conversions that I think at first. (I just mean that there are many extra checks, when only need the `==` but its what we see) – Aristos Jun 29 '12 at 11:36
  • I must tell you that is need some more code because the '==' is not work on this case...-> `site.com?ParamName=One&ParamName=Dyo&ParamName=OneMore` note that I have place the ParamName more than one times – Aristos Jun 29 '12 at 11:44
  • This is definitely nice and reusable proposal. – Anton Kalcik Jan 10 '19 at 12:07