What's the "correct" way to convert data from one type to another?

I'm curious what is the "correct" way to convert built-in types in .NET. I am currently using Convert.To[type]([variable])

without any zero checking or whatever. What's the best way to do this?

+2


source to share


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


See the link.



For the most part, the casting says, "This object of type A is indeed an object of type B-derived from -A." The Convert.To * () functions say this object is not type B, but there is a way to convert to type B. "

+3


source


Some types, such as int

( Int32

), have a method TryParse

. If such a method exists, I try to use it. Otherwise, I am doing a null check, but pretty much Convert.To

as you described.

Not sure if there is a "correct" way, like most tasks, it is contextual.

Kindness,

Dan

+2


source


It depends on situation. My best advice is to study and become familiar so you can make better choices on your own, but you should probably start by studying the following

System.Int32.TryParse()

      

(there are equivalents for most of the base types)

DateTime.ParseExact ()

+1


source







All Articles