Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null strings?

Tags:

c#

.net

asp.net

Say I have the following code:

Request.QueryString["ids"].Split('|');

If ids is not present in the query string this will throw an exception. Is there a generally accepted way to handle this type of situation. I think all of the following options would keep this from thorwing an error, but I'm wondering if one (or some different method entirely) is generally accepted as better.

string[] ids = (Request.QueryString["ids"] ?? "").Split('|'); 

or

string[] ids;
if(!String.IsNullOrEmpty(Request.QueryString["ids"]))
{
   ids = Request.QueryString["ids"].Split('|')
}

or

?

I think all of these will work, but they look sort of ugly. Is there a better* way?

*better = easier to read, faster, more efficient or all of the above.

like image 604
Abe Miessler Avatar asked Dec 12 '22 19:12

Abe Miessler


1 Answers

I like using an extension method for this:

public static string EmptyIfNull(this string self)
{
    return self ?? "";
}

Usage:

string[] ids = Request.QueryString["ids"].EmptyIfNull().Split('|');
like image 190
McGarnagle Avatar answered Dec 31 '22 06:12

McGarnagle