You can also mix decimal and numeric integral types in the same expression. However, mixing decimal and floating-point types without a cast causes a compilation error.
The following example causes a compiler error by trying to add double and decimal
variables.
double dub = 9;
// The following line causes an error that reads "Operator '+' cannot be applied to
// operands of type 'double' and 'decimal'"
Console.WriteLine(dec + dub);
// You can fix the error by using explicit casting of either operand.
Console.WriteLine(dec + (decimal)dub);
Console.WriteLine((double)dec + dub);
The result is the following error:
Operator '+' cannot be applied to operands of type 'double' and 'decimal'
In the following example, a decimal
and an int are mixed in the same expression. The result evaluates to the decimal
type.
public class TestDecimal
{
static void Main()
{
decimal d = 9.1m;
int y = 3;
Console.WriteLine(d + y); // Result converted to decimal
}
}
// Output: 12.1