8

I need explanations.. I using C#.NET to web applications, I always write:

 string val = Request.QueryString["foo"];

and then

if(!string.IsNullOrEmpty(val)) 

What's the difference:

string val = Request.QueryString["foo"];

I was advised to do:

string val = Request.QueryString["foo"] as string;
if(!string.IsNullOrEmpty(val)) 

What's the difference?

2 Answers 2

6

The first is better:

string val = Request.QueryString["foo"];

The second version returns null if the result of the call is not a string, but you know it always will be a string because the QueryString member has type NameValueCollection. The indexer is defined to return a string:

public class NameValueCollection : NameObjectCollectionBase
{
    // ...
    public string this[string name] { get; set; }
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

3

The as string is redundant as Request.QueryString["foo"] already is a string. (So there is no other difference than the second makes you look like you don't know your framework ;-) )

Comments

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.