views:

127

answers:

4

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?

+2  A: 

Some 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

Daniel Elliott
+1  A: 

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"

astander
That's pretty good.... +1.
David Stratton
I understand what a conversion *is* but i want to know the best way to do it.
RCIX
+1  A: 

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()

David Stratton
+3  A: 

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.

Ahmad Mageed
my favorite is when I see code like this: string test = "123"; txtBox.Text = test.ToString(); lol
Jack Marchetti