Search code examples
c#ternary

Convert if condition into ternary with C#


I would like to use ternary operator in order to factorize if condition.

I know the process : condition ? consequent : alternative

I have the if condition following :

if (!myField.IsNullOrNa())
    {
        messageErreur += myField.IsDecimalWithMessage(nameof(myField));
    }

I would like to write :

 messageErreur += !myField.IsNullOrNa() ? myField.IsDecimalWithMessage(nameof(myField)) : 

What I have to write as alternative ?


Solution

  • If you have multiple fields to check, simply make a small helper method that returns a string (or empty) based on a condition (boolean):

    messageErreur += Check(!myField.IsNullOrNa(), myField.IsDecimalWithMessage(nameof(myField)); 
    messageErreur += Check(myField.HasError(), myField.HasError(nameof(myField)); 
    
    private string Check(bool condition, string message) => condition ? message : string.Empty;