I'm curious as to what the "right" way to convert builtin types is in .NET. Currently i use Convert.To[type]([variable]) without any null checking or anything. What is the best way to do this?
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 is valid and won't throw an exception when the input to parse is null.
When it comes to converting items to a string, you can almost always rely on calling the ToString() method on the object. 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
One exception is calling ToString() on a nullable type, which would also return String.Empty.
int? x = null;
Console.WriteLine(x.ToString()); // no exception thrown
Thus, be careful when calling ToString; depending on the object, you may have to check for null explicitly.
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