Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a ternary operator - or similar method - for picking the variable to assign to?

is it possible to differ the variable I'm assigning to depending on a condition? The issue I came across is wanting to do this:

(bEquipAsSecondary ? currentWeaponOffhand : currentWeaponMainhand) = weaponToSwitchTo;

Instead of

if (bEquipAsSecondary)
{
    currentWeaponOffhand = weaponToSwitchTo;
}
else
{
    currentWeaponMainhand = weaponToSwitchTo;
}

Which results in the following error

Error CS0131 The left-hand side of an assignment must be a variable, property or indexer

So I was wondering if there was a way to do this to cut down on space used and - in my opinion - make it look a bit neater?

like image 508
JimLikesCookies Avatar asked Nov 18 '18 14:11

JimLikesCookies


2 Answers

To use terinary operator for picking the variable to assign value to, you could make use of ref locals/returns.For example,

(bEquipAsSecondary ? ref currentWeaponOffhand : ref currentWeaponMainhand) = weaponToSwitchTo;

Sample Output and Code

var currentWeaponOffhand = 4;
var currentWeaponMainhand = 5;
var weaponToSwitchTo = 7;

(bEquipAsSecondary ? ref currentWeaponOffhand : ref currentWeaponMainhand) = weaponToSwitchTo;
Console.WriteLine($"When bEquipAsSecondary={bEquipAsSecondary},currentWeaponOffhand={currentWeaponOffhand},currentWeaponMainhand={currentWeaponMainhand}");

Output

When bEquipAsSecondary=False,currentWeaponOffhand=4,currentWeaponMainhand=7
When bEquipAsSecondary=True,currentWeaponOffhand=7,currentWeaponMainhand=5
like image 58
Anu Viswan Avatar answered Sep 19 '22 13:09

Anu Viswan


Not sure if a ternary operator is a better choice than a regular if-else statement here. But you can use Action, something like this:

(bEquipAsSecondary ? new Action(() => currentWeaponOffhand = weaponToSwitchTo)
                   : () => currentWeaponMainhand = weaponToSwitchTo)();
like image 34
Salah Akbari Avatar answered Sep 17 '22 13:09

Salah Akbari