Conditional operator?
.net, c#, conditional-operator, ternary-operator
Solution
`?:` is the ternary operator. `??` is the null-coalescing operator. It is used to return the first expression that is not null.
The snippet you posted is making use of both operators. It is equivalent to the following `if/else` construct:
if (i == 1)
{
if (definition.SecondPetDiscount != null)
{
discount = definition.SecondPetDiscount;
}
else
{
discount = definition.AdditionalPetDiscount;
}
}
else if (i == 2)
{
if (definition.ThirdPetDiscount != null)
{
discount = definition.ThirdPetDiscount;
}
else
{
discount = definition.AdditionalPetDiscount;
}
}
else
{
discount = definition.AdditionalPetDiscount;
}
In that snippet they are chaining together multiple ternary operations. It is also sometimes useful to chain together multiple null-coalescing operations, e.g. `var foo = a ?? b ?? c`.
Problem
``` var discount = (i == 1) ? definition.SecondPetDiscount ?? definition.AdditionalPetDiscount : (i == 2) ? definition.ThirdPetDiscount ?? definition.AdditionalPetDiscount : definition.AdditionalPetDiscount; ``` Could you any one give me an explanation of this code snippet? I know about the ternary operator. But the above is not like that. The normal ternary operator looks like this: ``` PaidDate = ( paidDate == null ? DateTime.Now : paidDate); ```