Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration in a C# switch statement [duplicate]

People also ask

What is variable declaration in C?

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable.

What is declaration in C with example?

A "declaration" establishes an association between a particular variable, function, or type and its attributes. Overview of Declarations gives the ANSI syntax for the declaration nonterminal. A declaration also specifies where and when an identifier can be accessed (the "linkage" of an identifier).

Where do you declare variables in C?

The convention in C is has generally been to declare all such local variables at the top of a function; this is different from the convention in C++ or Java, which encourage variables to be declared when they are first used.

What are the 3 types of variables in C?

There are many types of variables in c: local variable. global variable. static variable.


If you want a variable scoped to a particular case, simply enclose the case in its own block:

switch (Type)
{
    case Type.A:
    {
        string variable = "x";
        /* Do other stuff with variable */
    }
    break;

    case Type.B:
    {
        string variable = "y";
        /* Do other stuff with variable */
    }
    break;
}

I believe it has to do with the overall scope of the variable, it is a block level scope that is defined at the switch level.

Personally if you are setting a value to something inside a switch in your example for it to really be of any benefit, you would want to declare it outside the switch anyway.


Yes, the scope is the entire switch block - unfortunately, IMO. You can always add braces within a single case, however, to create a smaller scope. As for whether they're created/allocated - the stack frame has enough space for all the local variables in a method (leaving aside the complexities of captured variables). It's not like that space is allocated during the method's execution.


Because their scope is at the switch block. The C# Language Specification states the following:

The scope of a local variable or constant declared in a switch block is the switch block.