Ahkam Nihardeen
Ahkam Nihardeen

Reputation: 147

What is the best way to write multiple if tags that compare two variables

I am a beginner in C# coding, and I was trying to compare two int variables (C#).

void CompareNumber() {
    int oneNumber;
    int secondNumber;

    if (oneNumber > secondNumber)
        {
        DoSomething();
        }

    else if (oneNumber < secondnumber)
        {
        DoSomethingElse();
        }

    else if (oneNumber == secondnumber)
         {
         DoSomethingDifferent();
         }
}

While this does work, it looks kinda messy, especially because I compare variables in this manner many times. Is there a more concise way of doing this, making it look neater? (Except for omitting the curly brackets)

Upvotes: 0

Views: 256

Answers (4)

Lewis Strasburg
Lewis Strasburg

Reputation: 31

Since you're asking for general ways to make if statements look tidier, consider the conditional operator "?:" if you're assigning a value. It doesn't work for calling void functions, but if, for instance, you wanted to return the higher of the two int values with CompareNumber(), you could do this:

int CompareNumber(int first, int second)
{
    return first > second ? first : second;
}

Can't say I see any simple ways to make your sample code more elegant though. If you have three different cases to implement, you can't skip anything. Of course I could be smart alec and simplify your function for you (and it wouldn't have errors for using uninitialized variables):

void CompareNumber()
{
    DoSomething();
}

EDIT: Previously stated you can't call functions with the conditional operator, but I meant you can't call void functions... they must return a value or you'll get a compiler error.

Upvotes: 1

HABO
HABO

Reputation: 15816

You can use a switch on the signum of the delta:

switch ( Math.Sign( Alpha - Beta ) )
{
case -1: // Alpha < Beta.
    // Do something.
    break;
case 0: // Alpha == Beta.
    // Do something.
    break;
case 1: // Alpha > Beta.
    // Do something.        
}

You can, of course, use the default clause in the switch to handle the final case.

Upvotes: 1

Rufus L
Rufus L

Reputation: 37020

You can shorten it using ternary operators, but you're doing it correctly.

void CompareNumber(int first, int second) {

    (first > second)
        ? DoSomething()
        : (second > first)
            ? DoSomethingElse()
            : DoSomethingDifferent();
}

Upvotes: 1

hatcyl
hatcyl

Reputation: 2352

The way you already wrote it is the best way :) There is absolutely nothing wrong with it.

However, when you say "especially because I compare variables in this manner many times", there may be something to fix there. Ideally, you should be able to reuse what you wrote one time.

Upvotes: 3

Related Questions