views:

122

answers:

3
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?

+6  A: 

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.

Mehrdad Afshari
+14  A: 

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.

Jon Skeet
Thanks for the tip on the TryGetValue!
Scott Chamberlain
+3  A: 

The statement is fine, && will short circuit, which means the right hand side is contingent upon the left. So if TryParse returns true, then expenseCode will be populated with a valid integer, and then the right function will execute.

Anthony Pegram