Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return this variable using if statements?

Tags:

c#

boolean

I know this might be a silly question, with an easy answer, but after an hour of searching the internet I could not find a way to do this;

    public bool GetCollision(int x, int y)
    {
        bool isPassable;

        if (x < 0 || x >= 20)
        {
            isPassable = false;
        }

        if (y < 0 || y >= 20)
        {
            isPassable = true;
        }

        return isPassable;
    }

On the second-to-last line it says that isPassable is unassigned... yet clearly I assign to it in the if statements. There must be some fundamental misunderstanding of "if" statements on my part.

So, how can I do this? Thank you very much.

like image 471
Sean Heiss Avatar asked Dec 19 '12 07:12

Sean Heiss


People also ask

How do you return a value from an if statement?

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")

Can I use return in if statement?

Yes. The return here will take the control out of method.

How do you use variables in IF statements?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.

Can you make a variable in an if statement?

An if-then statement can be used to create a new variable for a selected subset of the observations. For each observation in the data set, SAS evaluates the expression following the if. When the expression is true, the statement following then is executed.


1 Answers

That is because it doesn't have a default value set explicitly. Set isPassable to False by default and you're done.


Also you can do something like this:

return (!(x < 0 || x >= 20) && (y < 0 || y >= 20))

EDIT: The above solution would only work if an AND relationship would exist between your IFs.

like image 133
dutzu Avatar answered Nov 15 '22 01:11

dutzu