Inline IF Statement in C#

后端 未结 5 1480
不知归路
不知归路 2020-12-29 01:13

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 val

相关标签:
5条回答
  • 2020-12-29 01:44

    This is what you need : ternary operator, please take a look at this

    http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx

    http://www.dotnetperls.com/ternary

    0 讨论(0)
  • 2020-12-29 01:50

    Enum to int: (int)Enum.FixedPeriods

    Int to Enum: (Enum)myInt

    0 讨论(0)
  • 2020-12-29 01:53

    You can do inline ifs with

    return y == 20 ? 1 : 2;
    

    which will give you 1 if true and 2 if false.

    0 讨论(0)
  • 2020-12-29 01:58

    You may define your enum like so and use cast where needed

    public enum MyEnum
    {
        VariablePeriods = 1,
        FixedPeriods = 2
    }
    

    Usage

    public class Entity
    {
        public MyEnum Property { get; set; }
    }
    
    var returnedFromDB = 1;
    var entity = new Entity();
    entity.Property = (MyEnum)returnedFromDB;
    
    0 讨论(0)
  • 2020-12-29 02:00

    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.

    0 讨论(0)
提交回复
热议问题