I’m a newbie to C# and .NET, so I apoligize if this is a too simple question.
I have a decimal variable decVar.
I need to multiply it with an integer variable intVar.
I need the result to be decimal.
So should I then declare the integer variable as int or as decimal?
Having this code,
decimal decVar = 0.1m;
decimal decRes = decVar * intVar;
should I declare it like this:
int intVar = 3;
or like this:
decimal intVar = 3;
?
This is a financial calculation, so I need the result to be exactly 0.3.
upd : Code updated (thanks to Jon)
It doesn’t matter – the
intwill be converted todecimalanyway: there isn’t a*(decimal, int)operator, just*(int, int)and*(decimal, decimal). (And other types, of course.)Now
decimalcan’t be implicitly converted toint, but the reverse conversion is valid – so that’s what the compiler does.However, you’ll need to change the declaration of
decVaras currently the right hand side of the assignment operator is a double, not a decimal. You mean 0.1m. You’ll want semi-colons too 🙂