[c#] 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.

This question is related to c#

The answer is


You can do inline ifs with

return y == 20 ? 1 : 2;

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


Enum to int: (int)Enum.FixedPeriods

Int to Enum: (Enum)myInt


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;

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