Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only assignment call increment decrement can be used as a statement

Tags:

c#

winforms

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.

like image 381
Zzz Avatar asked Oct 20 '25 12:10

Zzz


2 Answers

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.

like image 99
Jon Skeet Avatar answered Oct 23 '25 01:10

Jon Skeet


The conditional operator is not a replacement of an ifclause. 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();
like image 22
Tim Schmelter Avatar answered Oct 23 '25 01:10

Tim Schmelter