zaria khan
zaria khan

Reputation: 333

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?

Upvotes: 5

Views: 350

Answers (3)

mybirthname
mybirthname

Reputation: 18127

Just write separate method and don't use nested ? operators, because it is pain for everybody(unreadable, prompt to errors). What if tomorrow your type extend with 2 more Types, your Ternary operator will become hell.

public TypeOfA GetTypeOfAMethod()
{
    if(UnitType != null)
       return UnitType;

    if(ElevationType != null)
       return ElevationType;

    if(StructureType != null)
       return StructureType

    return null;

}

Upvotes: 1

Alfie Goodacre
Alfie Goodacre

Reputation: 2793

If you need to do this with ternary operators, you can format it for better clarity like this

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

You could also null coalesce, which is the ?? operator, this says if the object is not null, return it, if it is return this instead.

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

Upvotes: 3

Ann L.
Ann L.

Reputation: 13965

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.

Upvotes: 10

Related Questions