c# - Cast object to float -


protected void gridview1_rowdeleting(object sender, gridviewdeleteeventargs e) {     var fp18var = (float) (int)e.values[0]; } 

i'm getting

invalidcastexception - specified cast not valid

why doesn't work?

the value of e.values[0] is: 6 666,00

the problem you're running here c# cast operator means different things in different situations.

take example gave:

object num = 10; float fnum = (float)num; 

the c# compiler think telling this: "the variable num refers boxed float; please unbox , return boxed value."

you're getting error because it's not boxed float, it's boxed int.

the problem c# uses identical-looking syntax 2 totally unrelated operations: 'unbox' , 'numeric conversion'. here's example of cast means numeric conversion:

int num = 10; float fnum = (float)num; 

almost same code, , yet won't give error. , that's because c# compiler treats differently - code means: "please perform numeric conversion, converting integer stored in 'num' single-precision floating point value."

how know of these 2 utterly unrelated operations it's going choose? it's source , destination types. if you're converting 'object' value type, treated unbox. if you're converting 1 numeric type another, treated numeric conversion.

so how result want? well, need both operations: need unbox int , need convert float. need 2 casts:

object num = 10; float fnum = (float) (int)num;  

horrible huh?

the simplest way want here avoid casting entirely. this:

float fnum = convert.tosingle(num);  

that coerce type single-precision float if it's possible so.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -