I have next code:
static void Main(string[] args)
{
byte currency;
decimal amount;
if (Byte.TryParse("string1", out currency) && Decimal.TryParse("string2", out amount))
{
Check(currency, amount);
}
Check(currency, amount); // error's here
}
static void Check(byte b, decimal d) { }
and get next error:
Use of unassigned local variable
‘amount’
Why am I getting it at all and this is legal, why only for amount? Why currency in this case is assigned and amount – not?
Look at this line (which I’ve separated onto two lines):
The
&&operator is a short-circuit evaluation, which means that if the firstByte.TryParsedoes not succeed, then the secondDecimal.TryParsewill never get executed at all.currencywill always be assigned becauseTryParsesets theout currencyref to the default value if it fails to parse. However,amountwill still be undefined in this case. It’s as if you wrote the code like this:This should make it more obvious what’s going on. The part inside the first
ifstatement always gets executed and assigns a value tocurrency. The part inside the second, nestedifstatement will only get executed if the first one succeeded. Otherwise,amountwill have no value by the time you hit the secondCheck.If you want to use the default values if the
currencycan’t be parsed, then just initialize the locals to the default values:Or you can simply parse both of them, as @Martin said.