casting

  • Thread starter Thread starter ichor
  • Start date Start date
I

ichor

hi

i am wondering why my first line works but the 2nd doesnt.

float f;

f= Convert.ToSingle (IntegerTextBox.Text) ;


f = (float) (IntegerTextBox.Text ); //ERROR cannot convert from string to
float

thanx
 
ichor said:
f= Convert.ToSingle (IntegerTextBox.Text) ;

This makes an explicit call to a method returning float and accepting
a string argument. There are no typecasts necessary to execute this
operation.
f = (float) (IntegerTextBox.Text ); //ERROR cannot convert from string to

Here you are attempting a type cast. There are a lot of things that could
go wrong here (Text might not be a number, it might not be formatted
correctly for the current locale, it may overflow or underflow the range
a float can represent). Essentially, effort is required to convert the text
representation of a floating-point number to its binary form. Whereas
Convert.ToSingle( ) (or alternately, float.Parse( )) make this work, and
the exceptions it can present, explicit ... a typecast to float does not.


Derek Harmon
 
Back
Top