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?
views:
127answers:
4Some types such as int
(Int32
) have a TryParse
method.
If such a method exists, I try to use that.
Otherwise, I do a null check then pretty much Convert.To
as you outlined.
Not sure if there is a "right" way, like most tasks it is contextual.
Kindness,
Dan
See this link.
For the most part, casting says "This object of type A is really an object of type B-derived-from-A" Convert.To*() functions say This object isn't a type B, but there exists a way to convert to type B"
It depends on the situation. My best advice would be to study up and become familiar, so you can make better choices on your own, but you should probably start by looking into the following
System.Int32.TryParse()
(there are equivalents for most base types)
DateTime.ParseExact()
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.