Let’s say I want to convert a Double x to a Decimal y. There’s a lot of ways to do 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, all of the above do the same thing (as far as I can tell). Other than personal taste and style, is there a particular reason to choose one option over the other?
EDIT: This is the IL generated by compiling the three C# options 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 the IL generated by compiling the four VB options 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 up in System.Decimal::.ctor(float64)
Convert.ToInt32()applies rounding to real numbers while casting to int just removes the fractional part. In my opinion typecasting method for “conversions” relies on .NET framework’s magic too much. If you know that a conversion will have to take place, describing it explicitly is the easiest to understand. I would go forConvertoption for most of the cases unless there is no conversion needed and a cast just works.