What, if any, is the difference between?
decimal d = (decimal) myDouble;
decimal d = new decimal(myDouble);
decimal d = Convert.ToDecimal(myDouble);
What, if any, is the difference between?
decimal d = (decimal) myDouble;
decimal d = new decimal(myDouble);
decimal d = Convert.ToDecimal(myDouble);
There is no difference. If you look at the source:
In Decimal:
public static explicit operator decimal(double value)
{
return new decimal(value);
}
In Convert:
public static decimal ToDecimal(float value)
{
return (decimal) value;
}
So in the end they all call new decimal(double)
.
They all achieve the same results. However, here's a more broken down explanation:
Method 1 creates a new variable which explicitly casts myDouble
to type decimal
. When you cast, you're saying, "This object of type A is really an object of type B-derived-from-A or a casting operator exists to cast A to B."
Method 2 creates a new variable which will convert myDouble
to the appropriate type (decimal
) via a constructor overload. When you invoke a constructor, you're saying, "Create a new object based on the arguments passed into the constructor."
Method 3 converts a base data type (double
) to another base data type (decimal
).
When you use something like Convert.ToDecimal()
, you're saying, "This object isn't of type B, but there exists a way to make it into an object of type B."
Regarding Convert
MSDN states:
A conversion method exists to convert every base type to every other base type. However, the actual conversion operation performed falls into three categories:
A conversion from a type to itself simply returns that type. No conversion is actually performed.
There is not any difference, actually, from functional point of view. These are different ways to achieve the same result.
Important to mantion that in case of Convert.ToDecimal, you have a possibility to specify a format IFormatProvider(culture), so you gain more flexibility.
If you don't care about multiculture environment, pick any of them you like.