Dimitris Sapikas
Dimitris Sapikas

Reputation: 622

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 !

Upvotes: 9

Views: 8548

Answers (4)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239646

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?

Upvotes: 16

tpeczek
tpeczek

Reputation: 24125

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);

Upvotes: 4

MX D
MX D

Reputation: 2485

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

Upvotes: 3

Yaakov Ellis
Yaakov Ellis

Reputation: 41490

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);

Upvotes: 6

Related Questions