What is the difference between Cast and Convert int i1 = 5;double d1 = i1 + 0.99;int i2 = (int)d1; //result is 5i2 = Convert.ToInt32(d1);//result is 6Why does cast and convert in above example have different results.

Questions by vsateeshk   answers by vsateeshk

Showing Answers 1 - 9 of 9 Answers

samiksc

  • Jul 11th, 2007
 

Cast always works - truncates the number being cast to different data type
and may result into an invalid value. Cast operation will not throw exception.

e.g.

double d = 123456789.1234;short i = (short)d;

Console.WriteLine(i);

int j = Convert.ToInt16(d);

Console.WriteLine(j);


The cast works and gives a meaningless negative value as output.
Convert.ToInt16 results into OverflowException being thrown.

Sometimes this is desirable since the errors generated due to wrong truncating
are hard to detect.

Other differences are some casts like casting from string to int is not allowed.
But Convert functions are available which do this conversion.

  Was this answer useful?  Yes

ChandimaP

  • Sep 23rd, 2007
 

Convert will correctly converts a number from one format to another if possible.
However, Cast ignores the encoding format of the data type. It deals directly with the encoded binary values of the data. Therefore, if the interpretation of the encoding of two data types are different, a cast will make the value incorrect.

  Was this answer useful?  Yes

convert internally call parse method for conversion implicitly. If we are using convert for conversion and the object is null than it will return 0 value while if we r using cast then it will give null reference exception during compilation. String str=null;Int temp=convert.toint32 (str);                          //return 0 valueOr, int temp= (Int32) str;                                    //throw exception during compilation

Converting performs a conversion -- it changes the VALUE returned (and often the type as well). Casting always returns the SAME value, but as a different type.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions