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?

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

7

You can use String.IsNullOrEmpty

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

Or

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

}

1 Comment

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).
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");

5 Comments

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.
Happy to accept criticism but can you explain how the code is considered to be 'slow'?
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)
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
This is definitely nice and reusable proposal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.