Most elegant way of checking the value of a query string parameter if not null?
23,146
Solution 1
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
Solution 2
You can use String.IsNullOrEmpty
String.IsNullOrEmpty(Page.Request.QueryString["ParamName"]);
Or
var parm = Page.Request.QueryString["ParamName"] ?? "";
if(parm == expectedResult)
{
}
Solution 3
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");
Author by
Admin
Updated on June 30, 2020Comments
-
Admin almost 4 years
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?
-
Admin almost 12 yearsWhat 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).
-
Aristos almost 12 yearsIs 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. -
Kane almost 12 yearsHappy to accept criticism but can you explain how the code is considered to be 'slow'?
-
Aristos almost 12 yearsBecause 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 almost 12 yearsI 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 -
Anton Kalcik over 5 yearsThis is definitely nice and reusable proposal.