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

  • A+
Category:Languages

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?

 


Not sure if this is really efficient, but if you really want to stick to ternary operator, here is my 2 cents...

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: