Tuesday, May 16, 2023

The scope of the variable in C# switch case

If we go for interviews regularly, everything is evident when we look at the code below. Otherwise, there are chances of confusion will it work? Also as managers who didn't look at code for a while, we may get slightly confused.

Will the above code compile?

Why not? Oh, look where the variable msg is declared. How can it be available in case 2: and default blocks?

That case is not a block, the switch is the block. In C# the block is associated with the curly brackets/braces. The variable will be kind of hoisted and available to the entire block following the declaration of the variable?

Wait, what is hoisting?

Don't remember JavaScript? Its interpreter moves all the declarations to the top of their scope. The C# compiler does something comparable to that.

Can we have scope inside the case statement?

Yes. Have a look at the below code.

Is this C# feature documented anywhere?

Yes right in the specs.

Read the specs and happy coding


No comments: