prime_crime
prime_crime

Reputation: 41

C# - basic if statement inquiry - can't find the answer

this has probably been answered but i don't know how to frame the question, therefore can't find a past answer.

so what i wanna do is something like this: (more variables for the same if check)

if ((aa && bb && cc) == 1)
    {
       win = 1;
    }

what's the correct syntax for this?

thanks a bunch

Upvotes: 2

Views: 129

Answers (6)

Al00X
Al00X

Reputation: 1614

You can use this code , and its very simple and easy

if ( aa == 1 && bb == 2 && cc == 3)
{
    // your codes
}

Upvotes: 0

tkellehe
tkellehe

Reputation: 679

The data type of the variable does make a difference as to what you could do with the if statement.


Boolean

If they are boolean values and you want to know when they are one, you can go:

if(aa && bb && cc) { }

Because each variable is either one or zero, if one of them were false then the whole statement would be false. Only, when all are one will this statement be true.


Integer

If you want to have the look of

if((aa && bb && cc) == Value) {}

You can multiply them and see if they are equal to the cube of Value.

if(aa*bb*cc == Value*Value*Value) {}

So, if Value equals one then you get:

if(aa*bb*cc == 1) {}

Best Way

The best way to do this would be to individually check that each variable is equal to Value.

if(aa == Value && bb == Value && cc == Value) {}

This is because the && operator expects two bools then returns a boolean value. So, when you go aa && bb && cc you are literally "anding" these values together to produce a boolean value. By first comparing each variable to the Value you are creating a boolean value for each one then "anding" that together to produce a similar result as the first solution I presented.


Hope this helps!

Upvotes: 1

You could check each variable individually, such as the following:

if (aa == 1 && bb == 1 && cc == 1)
{
    // do something
}

If you know that you'll always be checking against the value of 1, you may want to declare it as a constant.

public const int ExpectedValue= 1;
if (aa == ExpectedValue&& bb == ExpectedValue&& cc == ExpectedValue)
{
    // do something
}

Upvotes: 1

K. Bishop
K. Bishop

Reputation: 62

I am afraid you will have to do it the long way, There is no simple short clean way of checking if multiple vars have the same value in an if statement.

Code:

If (aa == 1 && bb == 1 && cc == 1)
{
    // Code here.
}

Hope this helps.

Upvotes: 1

Hardik Gondalia
Hardik Gondalia

Reputation: 3717

if you have many variables, you could also build an array of the values and use the IEnumerable.All method to verify they're all 1. More readable, IMO.

if (new[] { aa, bb, cc}.All(x => x == 1))

Upvotes: 2

Guy
Guy

Reputation: 50809

if (aa == 1 && bb == 1 && cc == 1)
{
   win = 1;
}

Upvotes: 1

Related Questions