9

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 !

4 Answers 4

16

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?

Sign up to request clarification or add additional context in comments.

4 Comments

However, the question is more about scopes. Title: "declare variable into if statement" exception: "The name 'a' does not exist in the current context"
@TimSchmelter That's splitting hairs, to be honest. This addresses that, perhaps in a roundabout way that directs the user to an alternative and thinking they're new to, but still.
@GrantThomas: Imho titles and questions are not so unimportant on SO, allthemore for future visitiors who are looking for an answer why they get this exception and why they cannot use a variable outside of an if. So one or two words about it or a link would have been helpful.
@TimSchmelter Precisely, you're right. With the knowledge now gained of the OPs actual problem, more properly framed, the title should be changed.
6

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

Comments

4

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.