4

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?

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

Nice. We'll see which one he picks!
Ahah. Last time @newStackExchangeInstance and I (like 30 minutes ago) answered the same questions 30 seconds apart, I won. I feel this one should go to him. So +1 to him. ;)
Thanks for answers, think this one goes to Simon as he was first to answer!
4

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.

Comments

2

Why not use the null coalescing operator?

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

3 Comments

Well, actually, it compiles to the same code. Don't believe me? ericlippert.com/2013/06/17/…
I wasn't saying that it doesn't, just stating that the null-coalescing operator is more readable.
I know, just interesting fact of the day :)
0

Different approach, while a bit more code, I think is more clear the intent.

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

2 Comments

While this is good, It feels dirty to me to access a dictionary value twice (even though it's O(1) in most cases). Also, it could be reduced to !String.IsNullOrWhitespace(Request.QueryString["mode"]) && Request.QueryString["mode"].Equals("advanced")
@SimonBelanger good point about dictionary access, in that case I would use your ?? method myself too :)
0

what about this

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

1 Comment

Looking for a one liner really as this problem is a common occurance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.