Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration in an if statement

In C# for a relatively simple program I am writing I am trying to create an event handler function that will handle multiple sources, like so:

private void fooHandler(object sender, RoutedEventArgs e)
{
    fooObject objectFoo = (fooObject)sender;
    if (objectFoo.name == "bla1"){
        bla1Window bla = new bla1Window();
    }
    if (objectFoo.name == "bla2"){
        bla2Window bla = new bla2Window();
    }
    .
    .
    .
    else{
        //default stuff happens
    }
bla.Left = this.Left
bla.Top = this.Top
bla.Show();
this.Close();
}

The function is for window switching. The problem is the variable falls out of scope as soon as I exit the if-statement. I'm doing it this way because, looking at the series of functions I've defined to handle each event individually, they are all the same with the exception of the one variable declaration. Is there a way to make this work, or am I just going to have to stick with a function for each event handler?

like image 626
Will Avatar asked Sep 01 '11 18:09

Will


People also ask

Can I declare a variable in an if statement?

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 declare a variable in an if statement in C?

No. That is not allowed in C. According to the ANSI C Grammar, the grammar for the if statement is IF '(' expression ')' statement . expression cannot resolve to declaration , so there is no way to put a declaration in an if statement like in your example.

Can you declare a variable in an if statement JS?

You can either use a ternary operator or declare the variable outside the if / else statement and define the variables value inside the if / else .

Can you define variable in IF statement Python?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.


1 Answers

If bla1Window and bla2Window both share a base class or interface, you can refer to them that way. In this case, it looks like you're just accessing properties of Window, so you could do:

Window window = null;
fooObject objectFoo = (fooObject)sender;
if (objectFoo.name == "bla1"){
    window = new bla1Window();
}
else if (objectFoo.name == "bla2"){
    window = new bla2Window();
}
.
.
.
else{
    //default stuff happens
}

window.Left = this.Left
window.Top = this.Top
window.Show();
this.Close();
like image 127
Reed Copsey Avatar answered Oct 26 '22 07:10

Reed Copsey