Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline IF Statement in C#

Tags:

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.

like image 348
Landi Avatar asked Aug 16 '12 06:08

Landi


People also ask

What is single line statement in C?

Single line comments are represented by double slash \\. Let's see an example of a single line comment in C. #include<stdio.h> int main(){ //printing information.

What is ternary operator in C?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");

What is conditional operator in C with example?

A conditional operator is a single programming statement, while the 'if-else' statement is a programming block in which statements come under the parenthesis. A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else' statement cannot be used for the assignment purpose.

What is conditional statement in C?

C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.


2 Answers

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.

like image 183
chiccodoro Avatar answered Oct 01 '22 09:10

chiccodoro


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; 
like image 28
user854301 Avatar answered Oct 01 '22 08:10

user854301