s.e
s.e

Reputation: 197

Compare value of int

How can I test if value of int is for example 1,2,4 or 5? I thought i could do something like this but apparently not.

if(someInt == (1||2||4||5))

Upvotes: 0

Views: 128

Answers (6)

David Heffernan
David Heffernan

Reputation: 613612

You need to write your if statement like this

if (someInt==1 || someInt==2 || someInt==4 || someInt==4)

Or you could use a switch statement

switch (someInt)
{
    case 1:
    case 2:
    case 4:
    case 5:
        // do something
        break;
}

Breaking down your attempted code is quite interesting. You wrote:

if(someInt == (1||2||4||5))

I guess in your head you read it as, if someInt equals 1 or 2 or 4 or 5. And if computers behaved like humans then this would work. But we all know that computers don't behave like that!

The == equality operator, a binary operator, returns true when its two operands are equal. So that means, in your version, if it compiled, you would need someInt to be equal to (1||2||4||5). And for that to even be meaningful, we would need (1||2||4||5) to evaluate to a single value, instead of producing a compile error. And, if it did evaluate to a single value, then it could not have the meaning which you want. Because you want the test to return true when someInt is equal to one of four candidate values.

The bottom line is that == tests for exact equality between precisely two values.

Upvotes: 1

daniloquio
daniloquio

Reputation: 3912

You can't do it like that. Instead use:

if(someInt == 1 || someInt == 2 || someInt == 4 || someInt == 5)

Or also you could use something like this:

if((new List<int>() {1,2,4,5}).Contains(someInt) == true)

Upvotes: 0

ClassicThunder
ClassicThunder

Reputation: 1936

There are two ways I can think of.

Or all the comparisons.

if (someInt == 1 || someInt == 2 || someInt == 4 || someInt == 5) {

}

Or for a more flexible solution see if someInt is in an array.

if (Array.BinarySearch(new[] { 1, 2, 4, 5 }, someInt ) != -1) {

}

Upvotes: 1

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35156

Write an extension method

static class MiscExtensions
{
    static bool EqualToAny<T>(this T i, params T[] items)
    {
        return items.Any(x => x.Equals(i));
    }
}

And use it like so

static class Program
{
    static void Main(string[] args)
    {
        int myNumber = 5;
        if (myNumber.EqualToAny(1, 2, 3, 4, 5))
            Console.WriteLine("Hello, World");
    }
}

Upvotes: 3

Anthony Faull
Anthony Faull

Reputation: 18007

Use LINQ:

if ((new[] {1,2,4,5}).Contains(someInt))

Upvotes: 4

Frank Bollack
Frank Bollack

Reputation: 25196

As an alternative you can use:

switch(someInt)
{
   case 1:
   case 2:
   case 4:
   case 5:
      DoYourStuff();
      break;
}

Upvotes: 1

Related Questions