Converting numeric types: which style to use?

Let's say I want to convert Double x to decimal y . There are many ways to do this:

 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, all of the above does the same (as far as I can tell). Besides personal taste and style, is there a definite reason to choose one option over another?

EDIT . This is an IL generated by compiling three C # parameters in a Release configuration:

 1. call valuetype [mscorlib]System.Decimal [mscorlib]System.Convert::ToDecimal(float64) --> which calls System.Decimal::op_Explicit(float64) --> which 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) --> which calls System.Decimal::.ctor(float64) 

This is an IL generated by compiling four VB parameters in a Release configuration:

 1. call valuetype [mscorlib]System.Decimal [mscorlib]System.Convert::ToDecimal(float64) --> which calls System.Decimal::op_Explicit(float64) --> which 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 it all ends with System.Decimal::.ctor(float64)

+7
source share
3 answers

Convert.ToInt32() applies rounding to real numbers, and casting to int just removes the fractional part. In my opinion, the machine translation method for "conversions" depends too much on the magic of the .NET framework. If you know that a transformation is about to happen, its description is clearly the easiest to understand. I would go for the Convert option for most cases if there is no need for conversion and just a throw is performed.

+4
source

I would suspect that using a unary casting operator will give the compiler a better chance of optimization, but I'm basing this on absolutely nothing.

+6
source

With non-object and non-string source data types, I prefer castings. Brief and easy to read.

For object types and string sources, this depends on the source. For example, if the source belongs to the user, then I use the Convert / Conversion methods.

I recommend downloading the source code for .NET in the "Microsoft Source Code Link Center" ( http://referencesource.microsoft.com ). Check out Convert.cs, Converstion.vb and Conversions.vb. Before, I would use Convert / Conversion methods in all cases, but after looking at these source files, I was given preference.

Taking your Convert.ToDecimal() example and referring to Convert.cs, the call is a really simple actor:

  public static decimal ToDecimal(double value) { return (decimal)value; } 
+1
source

All Articles