c# - Avoiding NullReferenceException in Request.QueryString -


this code throws nullreferenceexception if mode not specified in pages query string:

bool isadvancedmode = request.querystring["mode"].equals("advanced"); 

this how work around this:

bool isadvancedmode = (request.querystring["mode"] + "").equals("advanced"); 

is standard practise, or hack?

you can use null-coalescing operator:

bool isadvancedmode = (request.querystring["mode"] ?? string.empty).equals("advanced"); 

edit: if want re-use logic, try 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 match equals signature. i'm not sure if name (i think not).


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -