Reputation: 673
Can I create an instance of an object within an if statement? I've made 2 checkboxes in order to controll which constructor I use, but i get the error message " The name "mth" does not exist in the current context "
if (checkBox1.Checked && checkBox2.Checked)
{
Facto mth = new Facto(label3, wait_time, progressBar1);
}
else if(checkBox1.Checked==false && checkBox2.Checked)
{
Facto mth = new Facto(label3,wait_time);
}
else if (checkBox1.Checked && checkBox2.Checked == false)
{
checkBox1.Checked = false;
Facto mth = new Facto();
}
else
{
Facto mth = new Facto();
}
int result = mth.Factorial(number);
What am I doing wrong? I'm new to C# and I don't really have the hang of it yet. Any help would be appreciated. Thanks in advance.
Upvotes: 1
Views: 3480
Reputation: 312
The problem here is not creating instance inside if block. The mth reference is declared in the if/else blocks. This restricts the visibility/scope only to that block. so mth is not available when you try to refer it in line int result = mth.Factorial(number);
Just declare mth outside the if block and only instantiate inside if/else blocks. For ex:
Facto mth;
if (checkBox1.Checked && checkBox2.Checked)
{
mth = new Facto(label3, wait_time, progressBar1);
}
...
Refer http://msdn.microsoft.com/en-us/library/aa691132(v=vs.71).aspx for some basic information.
Upvotes: 0
Reputation: 5370
This is a scoping problem. The variable mth only exists within the scope (brackets in your case) that it's defined in. As soon as you leave the scope the variabel is no longer available. Since you use the mth
variable at the end of your code (and outside the scope) you get this error. In order to fix this you need to define the variable at a higher scope. Note that you don't have to assign it there.
This leads to something like (Note that I reformatted your brackets to make it easier to see the scope levels)
Facto mth; // Define it as the most outer scope level you are using it
if (checkBox1.Checked && checkBox2.Checked)
{
mth = new Facto(label3, wait_time, progressBar1);
}
else
if(checkBox1.Checked==false && checkBox2.Checked)
{
mth = new Facto(label3,wait_time);
}
else
if (checkBox1.Checked && checkBox2.Checked == false)
{
checkBox1.Checked = false;
mth = new Facto();
}
else
{
mth = new Facto();
}
int result = mth.Factorial(number);
EDIT: I would advice to always use {} brackets on every if and else even if they are not strictly required like in your case. As you can see in the layout it's not so easy to see where your first else ends and that the "int result line isn't part of it.
Upvotes: 1