String Conversion Alternatives - One Method Better Than Other?

R

RC

Just wondering if there are good reasons (performance, ?) to use one of
these string conversion alternatives over the other:
1. Convert.ToString()
2. someObject.ToString()

Example:
Convert.ToString(DataRow1["SomeValue"])
vs.
DataRow1["SomeValue"].ToString()

Thanks
 
T

Thomas P. Skinner [MVP]

They are semantically equivalent. There would be no difference in
performance. According to the FCL documentation the implementation is
"identical."

Thomas P. Skinner [MVP]
 
S

SevDer

RC said:
Just wondering if there are good reasons (performance, ?) to use one of
these string conversion alternatives over the other:
1. Convert.ToString()
2. someObject.ToString()

Example:
Convert.ToString(DataRow1["SomeValue"])
vs.
DataRow1["SomeValue"].ToString()

Thanks

Try to use .ToString()
Convert.ToString(theObject) assumes to make convertion from object, but
whenever you can use object.ToString() because specified objects
object.ToString() method would be more optimized for this kind of
operations.

And in your case use DataRow1["SomeValue"].ToString() as a preference.

PS: For data operations (not too heavy) you can prefer to use typed
datasets, and as a result you won't need to do type convertions.
 
M

Morten Wennevik

Hi RC,

The convert class is generally used when you need complex conversions.
As for Convert.ToString(someObject) vs someObject.ToString() use the
latter. The convert class only calls the object's ToString() method.

I rarely use the Convert class when only one parameter is involved.
In case of numbers you can easily just cast it to another type.
In case of ToString it is the same as calling the ToString method of the
number type or object anyway.

The Convert class is handy when you for instance need to convert a bool
to a numeric value, a cast is not allowed, or you need to read or write
hexadecimal or binary strings.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top