zaria khan zaria khan - 1 month ago 17
C# Question

Condition in Conditional (Ternary) Operator

How can I implement this using ternary operator?

if(UnitType == null)
{
a = ElevationType
}
else
{
a = UnitType
}


Ternary operator

a = UnitType == null ? ElevationType : UnitType;


Now I want something like this

if(UnitType == null)
{
if(ElevationType == null)
{
a = StructureType
}
else{
a = ElevationType
}
}
else
{
a = UnitType
}


Can I achieve this using ternary operator? If not, what should be done?

Answer
a = (UnitType == null) ? (ElevationType ?? StructureType) : UnitType;

But I stand by my comment: this is harder to understand than the if-else would be.

Or, possibly,

a = UnitType ?? ElevationType ?? StructureType;

That's reasonably clear if you're familiar with the ?? operator.

Comments