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.
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('|');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With