Condition in conditional (triple) operator

How can I implement this with a 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 the ternary operator? If not, what to do?

+4
source share
3 answers
a = (UnitType == null) ? (ElevationType ?? StructureType) : UnitType;

But I support my comment: this is harder to understand than if-else.

Or maybe

a = UnitType ?? ElevationType ?? StructureType;

This is understandable enough if you are familiar with the operator ??.

+9
source

If you need to do this using triple operators, you can format it for clarity, for example,

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

null coalesce, ??, , , , .

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

Just write a separate method and do not use nested operators ?, because it is a pain for everyone (unreadable, error hints). What if tomorrow your type expands with two more types, your Ternary statement will become hell.

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

    if(ElevationType != null)
       return ElevationType;

    if(StructureType != null)
       return StructureType

    return null;

}
+1
source

Source: https://habr.com/ru/post/1659068/


All Articles