I want to ask someone who has stronger skills than me in C#.
Is it possible to reduce the following code
if(val > 20 && val < 40 )
...
else
if(val > 40 && val < 72 )
...
else
if(val > 72 && val < 88 )
...
else
...
Let's assume that I have over 10-11 if-else
statements.
What's the best way to shorten the above code?
I thought at something like between
in sql.
if..else statements In an if...else statement, if the code in the parenthesis of the if statement is true, the code inside its brackets is executed. But if the statement inside the parenthesis is false, all the code within the else statement's brackets is executed instead.
We can use the else statement with if statement to execute a block of code when the condition is false. The block of code following the else statement is executed as the condition present in the if statement is false. A nested if in C is an if statement that is the target of another if statement.
The if statement is also known as a decision making statement, as it makes a decision on the basis of a given condition or expression. The block of code inside the if statement is executed is the condition evaluates to true.
This condition of C else-if is one of the many ways of importing multiple conditions. Decision making statements in programming languages decides the direction of flow of program execution. Decision making statements available in C or C++ are: if statement is the most simple decision making statement.
Define an extension method:
public static bool Between(this int source, int a, int b)
{
return source > a && source < b;
}
Then, use it:
if (val.Between(20, 40))
//...
As oɔɯǝɹ correctly pointed out in his comment, you could go one step further and support all implementers of IComparable<T>
with a generic extension method:
public static bool Between<T>(this T source, T a, T b) where T : IComparable<T>
{
return source.CompareTo(a) > 0 && source.CompareTo(b) < 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With