简体   繁体   中英

How better check Request.QueryString string parameter for null?

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?

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; }
    // ...
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM