Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# declare variable into if statement

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 !

like image 439
Dimitris Sapikas Avatar asked Feb 12 '13 08:02

Dimitris Sapikas


4 Answers

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?

like image 72
Damien_The_Unbeliever Avatar answered Sep 30 '22 02:09

Damien_The_Unbeliever


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);
like image 34
Yaakov Ellis Avatar answered Sep 30 '22 02:09

Yaakov Ellis


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);
like image 23
tpeczek Avatar answered Sep 30 '22 03:09

tpeczek


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

like image 22
MX D Avatar answered Sep 30 '22 01:09

MX D