c# - Convert numeric types: Which style to use? -
let's want convert double x
decimal y
. there's lot of ways that:
1. var y = convert.todecimal(x); // dim y = convert.todecimal(x) 2. var y = new decimal(x); // dim y = new decimal(x) 3. var y = (decimal)x; // dim y = ctype(x, decimal) 4. -- no c# equivalent -- // dim y = cdec(x)
functionally, of above same thing (as far can tell). other personal taste , style, there particular reason choose 1 option on other?
edit: il generated compiling 3 c# options in release configuration:
1. call valuetype [mscorlib]system.decimal [mscorlib]system.convert::todecimal(float64) --> calls system.decimal::op_explicit(float64) --> calls system.decimal::.ctor(float64) 2. newobj instance void [mscorlib]system.decimal::.ctor(float64) 3. call valuetype [mscorlib]system.decimal [mscorlib]system.decimal::op_explicit(float64) --> calls system.decimal::.ctor(float64)
this il generated compiling 4 vb options in release configuration:
1. call valuetype [mscorlib]system.decimal [mscorlib]system.convert::todecimal(float64) --> calls system.decimal::op_explicit(float64) --> calls system.decimal::.ctor(float64) 2. call instance void [mscorlib]system.decimal::.ctor(float64) 3. newobj instance void [mscorlib]system.decimal::.ctor(float64) 4. newobj instance void [mscorlib]system.decimal::.ctor(float64)
so, ends in system.decimal::.ctor(float64)
convert.toint32()
applies rounding real numbers while casting int removes fractional part. in opinion typecasting method "conversions" relies on .net framework's magic much. if know conversion have take place, describing explicitly easiest understand. go convert
option of cases unless there no conversion needed , cast works.
Comments
Post a Comment