Avoiding NullReferenceException in Request.QueryString

This code throws a NullReferenceException if mode not specified in the page request line:

 bool isAdvancedMode = Request.QueryString["mode"].Equals("advanced"); 

Here's how I get around this:

 bool isAdvancedMode = (Request.QueryString["mode"] + "").Equals("advanced"); 

Is this standard practice or hacking?

+4
source share
5 answers

You can use the null-coalescing operator :

 bool isAdvancedMode = (Request.QueryString["mode"] ?? String.Empty).Equals("advanced"); 

Edit: If you want to reuse 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 the Equals signature. I am not sure if this is a good name (I think it is not).

+7
source

Well, I would recommend this instead:

 bool isAdvancedMode = (Request.QueryString["mode"] ?? "").Equals("advanced"); 

Actually, this is what your code compiles into (closer to the bottom, but it reads well, so I would read everything), your good practice, but it's a little more clear.

+4
source

Why not use the null coalescing operator?

 bool isAdvancedMode = (Request.QueryString["mode"] ?? String.Empty).Equals("advanced"); 
+2
source

A different approach, while a bit more code, I think, a clearer intention.

 bool isAdvancedMode = String.IsNullOrWhitespace(Request.QueryString["mode"]) ? false : Request.QueryString["mode"].Equals("advanced") 
0
source

how about this

 bool isAdvancedMode=(Request.QueryString["mode"] ?? string.Empty).Equals("advanced"); 
0
source

Source: https://habr.com/ru/post/1492111/


All Articles