Avoiding NullReferenceException in Request.QueryString
asp.net, c#, nullreferenceexception, query-string
Solution
You can use the null-coalescing operator:
bool isAdvancedMode = (Request.QueryString["mode"] ?? String.Empty).Equals("advanced");
Edit: If you want to re-use this logic, try this extension method:
public static bool EqualIfExists(this string source, string comparison)
{
return source != null && source.Equals(comparison);
}
Request.QueryString["mode"].EqualIfExists("advanced")
Add more overrides to match `Equals` signature. I'm not sure if this is a good name (I think it is not).
Problem
This code throws a `NullReferenceException` if `mode` is not specified in the pages query string: ``` bool isAdvancedMode = Request.QueryString["mode"].Equals("advanced"); ``` This is how I work around this: ``` bool isAdvancedMode = (Request.QueryString["mode"] + "").Equals("advanced"); ``` Is this standard practise, or a hack?