-->

C# Casting to a decimal

2020-08-14 02:20发布

问题:

What, if any, is the difference between?

decimal d = (decimal) myDouble;
decimal d = new decimal(myDouble);
decimal d = Convert.ToDecimal(myDouble);

回答1:

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).



回答2:

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.

  • A conversion which cannot yield a meaningful result throws InvalidCastException. No conversion is actually performed. An exception is thrown for conversions from Char to Boolean, Single, Double, Decimal or DateTime, and from those types to Char. An exception is thrown for conversions from DateTime to any type except String, and from any type, except String, to DateTime. Any base type, other than those described above, can be converted to and from any other base type.


回答3:

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.