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?
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).
Well, I would recommend this instead:
bool isAdvancedMode = (Request.QueryString["mode"] ?? "").Equals("advanced");
In fact, this is what your code compiles to (Nearer the bottom, but it's a good read so I'd read it all). Yours is good practice, but this is a bit more clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With