i want to do something like this using C# :
if (i == 0)
{
button a = new button();
}
else
{
TextBlock a = new TextBlock();
}
mainpage.children.add(a);
But i get an error that
Error 1 The name 'a' does not exist in the current context
Any ideas ?
thank you in advance !
You need a common base class that both button
and Textblock
derive from, and it needs to be declared outside of the if
statement if it's to be accessed after the if
is complete. Control
maybe?
Control a;
if (i == 0)
{
a = new button();
}
else
{
a = new TextBlock();
}
mainpage.children.add(a);
Not knowing what specific control toolkit you're using (WPF maybe?) I can't advise further. But I'd look at the signature for Add
to get a clue - what's the parameter declared as?
Try declaring a
outside of the scope of the if/else. Like this:
Control a;
if (i == 0)
{
a = new button();
}
else
{
a = new TextBlock();
}
mainpage.children.add(a);
You need to declare your variable in parent scope and give it a common base class. The common base class for System.Windows.Controls.TextBlock
and System.Windows.Controls.Button
can be for example System.Windows.UIElement
or System.Windows.FrameworkElement
. So your code can look like this:
UIElement a;
if (i == 0)
{
a = new Button();
}
else
{
a = new TextBlock();
}
mainpage.children.add(a);
I found a discussion about declaring and assigning variables inside a condition here: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/11a423f9-9fa5-4cd3-8a77-4fda530fbc67
It seems it cannot be done in C#, even though you can in other languages
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