about ConvertTo and cast


T

tony

Hello!

What is the difference if I use double as cast as in (double)value

compare to using Convert.ToDouble(value)



//Tony
 
Ad

Advertisements

S

Sanjib Biswas

You should be using Convert class to do the type conversion as it uses
implicit conversions. Where as type casting a value, called explicit or
force conversion, there may be a data loss.
 
H

Hans Kesting

Hello!
What is the difference if I use double as cast as in (double)value

compare to using Convert.ToDouble(value)

//Tony
if "value" is a double, float, int (or other numerical type), I don't
think there is a difference.

if "value" is a boxed numerical type, but not a boxed decimal, then a
cast will result in a runtime error, while Convert gives the correct
result.
Example:
float f1 = 1.23f;
object o1 = f1;
double d1 = Convert.ToDouble(o1); // succeeds
double d2 = (double)f1; // succeeds, same result
double d3 = (double)o1; // CRASH

Hans Kesting
 
T

TheSteph

Example :

int tmpIntBad = (int) '1';
// the value of tmpIntBad is 49

int tmpIntGood = Convert.ToInt32('1');
//the value of tmpIntGood is 1
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

TheSteph said:
Example :

int tmpIntBad = (int) '1';
// the value of tmpIntBad is 49

int tmpIntGood = Convert.ToInt32('1');
//the value of tmpIntGood is 1
No.

Convert.ToInt32('1') also returns 49.

Convert.ToInt32("1") returns 1.

Arne
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

Sanjib Biswas said:
You should be using Convert class to do the type conversion as it uses
implicit conversions. Where as type casting a value, called explicit or
force conversion, there may be a data loss.
That's a massive overgeneralisation. If the type of value is already
numeric (or a boxed double) then a cast will do just as well as a call
to Convert (which can lead to exactly the same kind of data loss).
Convert is useful for parsing, or for using custom conversions.
 
Ad

Advertisements


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