Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding NullReferenceException in Request.QueryString

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?

like image 502
Tom Gullen Avatar asked Dec 11 '22 13:12

Tom Gullen


2 Answers

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

like image 76
Simon Belanger Avatar answered Dec 26 '22 07:12

Simon Belanger


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.

like image 39
It'sNotALie. Avatar answered Dec 26 '22 08:12

It'sNotALie.