Landi Landi - 6 months ago 53
C# Question

Inline IF Statement in C#

How will I write an Inline IF Statement in my C# Service class when setting my enum value according to what the database returned?

For example: When the database value returned is 1 then set the enum value to VariablePeriods, when 2 then FixedPeriods.

Hope you can help.


The literal answer is:

return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);

Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:

return (value == 1
    ? Periods.VariablePeriods
    : (value == 2
        ? Periods.FixedPeriods
        : Periods.Unknown));

If you add more values an inline if will become unreadable and a switch would be preferred:

switch (value)
case 1:
    return Periods.VariablePeriods;
case 2:
    return Periods.FixedPeriods;

The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.