This question reminded me of an old unanswered question in my mind about switch:
int personType = 1;
switch (personType)
{
case 1:
Employee emp = new Employee();
emp.ExperienceInfo();
break;
case 2:
Employee emp = new Employee();
//Error: A local variable named 'emp' is already defined in this scope
emp.ManagementInfo();
break;
case 3:
Student st = new Student();
st.EducationInfo();
break;
default:
MessageBox.Show("Not valid ...");
}
why is emp recognized in 'case 2'? in C++ (if I am not wrong) we could use multiple cases together, but in C# that is impossible and we should close case 1
with break so the following code seems right in C++ and wrong in C#:
case 1:
case 2:
SomeMethodUsedByBothStates();
When we can not have such behaviour so why should we be able to declare emp in case 1
and see it in case 2
? If never two cases happen together so why should the object be seen in both?
Cases do not create scope in c++ or in c#. All of those variables declared inside a case are in the same scope, that of the switch statement. You need to use braces if you want those variables to be local to some specific case:
switch (personType)
{
case 1: {
Employee emp = new Employee();
emp.ExperienceInfo();
break;
}
case 2: {
Employee emp = new Employee();
// No longer an error; now 'emp' is local to this case.
emp.ManagementInfo();
break;
}
case 3: {
Student st = new Student();
st.EducationInfo();
break;
}
...
}
The second code you showed is perfectly fine in C#, assuming case 2 had a break
or return
:
case 1:
// no code here...
case 2:
SomeMethodUsedByBothStates();
break;
Empty cases are allowed to fall through.
What is not allowed is to have code in a case-branch that falls through. So, the following would be invalid:
case 1:
SomeMethodUsedOnlyByCase1();
// no break here...
case 2:
SomeMethodUsedByBothStates();
break;
The question about the scope is a different one. Basically, the scope is the switch statement itself, not a case-branch.
To make your example compile, simply give the case-branches scopes of their own by adding curly braces:
int personType = 1;
switch (personType)
{
case 1:
{
Employee emp = new Employee();
emp.ExperienceInfo();
break;
}
case 2:
{
Employee emp = new Employee();
emp.ManagementInfo();
break;
}
case 3:
{
Student st = new Student();
st.EducationInfo();
break;
}
default:
MessageBox.Show("Not valid ...");
}
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