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?
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.
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.
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 .
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With