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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With