Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It is possible to define something like 'between' in if-else statement in C#?

Tags:

c#

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.

like image 445
Snake Eyes Avatar asked Sep 05 '12 19:09

Snake Eyes


People also ask

What is the difference between if and else in C++?

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.

How do you use the else statement with IF statement?

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.

What is the if statement also known as?

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.

What is the use of else-if condition in C?

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.


Video Answer


1 Answers

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;
}
like image 89
Adam Avatar answered Nov 15 '22 14:11

Adam