Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this if statment cause bad things to happen?

int expenseCode;
if (int.TryParse(sourceRecord.ExpenseCode, out expenseCode) && _ExpenseCodeLookup.ContainsKey(expenseCode))
{
     destRow.PROFIT_CENTER_NAME = _ExpenseCodeLookup[expenseCode];
}
else
     destRow.PROFIT_CENTER_NAME = "Unknown";

The thing I am conerned about is will the first expression always be run (setting expenseCode in the process) before the second operation?

like image 558
Scott Chamberlain Avatar asked Jun 23 '10 20:06

Scott Chamberlain


2 Answers

That's fine. && is short-circuiting in C#, and the out parameter will definitely have been assigned the appropriate value by TryParse before ContainsKey is called.

On the other hand, you could use the same trick again to fetch the value:

string profitCenter;
int expenseCode;
if (int.TryParse(sourceRecord.ExpenseCode, out expenseCode) && 
    _ExpenseCodeLookup.TryGetValue(expenseCode, out profitCenter))
{
    destRow.PROFIT_CENTER_NAME = profitCenter;
}
else
{
    destRow.PROFIT_CENTER_NAME = "Unknown";
}

This way you're only doing the lookup of the expense code once.

like image 58
Jon Skeet Avatar answered Oct 18 '22 13:10

Jon Skeet


No, it won't cause bad things to happen!

The && operator guarantees not to evaluate the right operand if the left operand evaluates to false. This is called short-circuiting.

Similarly, || operator will not evaluate the right operand if the left operand evaluates to true.

The non-short-circuiting versions of these operators for boolean values are & and |. They will evaluate both operands regardless of the value of the left hand side.

like image 22
mmx Avatar answered Oct 18 '22 13:10

mmx