What's the "correct" way to convert data from one type to another?
4 answers
Many types have a TryParse method that you could use. For example:
string input = null;
bool result;
Boolean.TryParse(input, out result);
// result ...
The above and will not throw an exception if the input to parse is null.
When it comes to converting items to a string, you can almost always rely on calling the object's ToString () method. However, calling it on a null object will throw an exception.
StringBuilder sb = new StringBuilder();
Console.WriteLine(sb.ToString()); // valid, returns String.Empty
StringBuilder sb = null;
Console.WriteLine(sb.ToString()); // invalid, throws a NullReferenceException
The only exception is the call to ToString () on a nullable type, which also returns String.Empty.
int? x = null;
Console.WriteLine(x.ToString()); // no exception thrown
Thus, be careful when calling ToString; depending on the object, you may need to explicitly specify null.
+3
source to share