简体   繁体   中英

Is it proper way to escape possible NullReferenceException with strings using Convert.ToString()?

Is this piece of code:

public string GetSomething(string someValue)
{
   var x = Convert.ToString(someValue);
   return x.SomeStringMethod(); // e.g. x.ToLower(); 
}

have any issues I should be concerned about in comparison to this:

public string GetSomething(string someValue)
{
   var x = someValue ?? string.Empty;
   return x.SomeStringMethod(); // e.g. x.ToLower(); 
}
Convert.ToString(x)

where x is of type string and is null, returns null , so it doesn't do the same thing as

someValue ?? string.Empty;

You must use the second approach to avoid null reference exceptions from the line

 x.SomeStringMethod();

More readable would be to just do:

if (someValue != null)
    return someValue.SomeStringMethod();
else
    return "";

If the string is empty and you want to return an empty string then i would sugest this:

var x = String.IsNullOrEmpty(someValue) ? string.Empty:someValue;
return x.SomeStringMethod();

Avoids the nullReferenceException and returns the empty string if empty or null,if not returns the actual string.

If by any chance you would like to tell the user that the result of that string is null you can do this:

var x = String.ReferenceEquals(someValue, null) ? "null" : someValue;
return x.SomeStringMethod();

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