The following line of code is causing the following "Only assignment call increment decrement can be used as a statement."
iRowsEffected == 0 ? trans.Rollback() : trans.Commit();
I have used the if else shorthand many times but have never received this error.
I have used the if else shorthand many times but have never received this error.
Then I suspect you've always used it properly before now.
The conditional operator isn't just "if / else" short-hand... it's syntax for evaluating an expression - the result of the expression is either the result of evaluating the second or third operand, based on the result of evaluating the first operand.
All three operands must be non-void, and the result of the expression has to be used somewhere - just like a property access, for example.
Here, you're just trying to execute one void method or another, so you want:
if (iRowsAffected == 0) // Fixed typo in name
{
trans.Rollback();
}
else
{
trans.Commit();
}
If you really, really, really want to use the conditional operator, you could use it for a method group conversion:
Action completion = iRowsAffected == 0 ? (Action) trans.Rollback : trans.Commit;
completion();
(You have to cast one of the second or third operands in order to provide a conversion for the other one, but it doesn't matter which and you don't need to cast on both of them.)
Or in one foul statement:
// Don't do this. Please.
(iRowsAffected == 0 ? (Action) trans.Rollback : trans.Commit)();
Please don't do this though. I've only included it for completeness.
The conditional operator is not a replacement of an if
clause. It is used to return two different values according to a boolean expression and assign this value to a variable. But both of your methods "return" void
and you don't assign anything here.
Here you need a simple if
-else
:
if(iRowsEffected == 0)
trans.Rollback();
else
trans.Commit();
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