Click here to Skip to main content
14,667,289 members
Rate this:
Please Sign up or sign in to vote.
See more:
Recently transitioned over from Java. I've initialized an array outside the local scope of my switch statement. However in each switch case I wish to populate the array in the case matched. For example:

int[] Stment = {};
....Code
switch (level)
           {
               case 5:
                   Stment = new int[] { 5, 10, 15, 20 };
                   break;
               case 50:
                   Stment = new int[] { 50, 60, 70, 80};
                   break;
           }
           string disp = string.Join(Environment.NewLine, Stment);
           MessageBox.Show(disp);</pre>

Is there a way for me to use the populated array outside the switch's local scope?
Posted
Updated 28-Dec-15 11:15am
v2
Comments
Sergey Alexandrovich Kryukov 28-Dec-15 17:28pm
   
What do you mean "is there"? You are already doing it.
—SA

Rate this:
Please Sign up or sign in to vote.

Solution 1

There are two ways: first is to assign a value took the variable when you define it.
int[] Stment = null;

Or
int[] Stment = new int[0];

Will do it.
Alternatively, add a default case to your switch block:
default: Stment = null;

Or
default: Stment = new int[0];

As long as the compiler can see any route through the code where the variable is not given a value before it is used, you will get that error - even if the logic actually prevents it happening.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

As the variable Stment is declared outside the switch context, you can use it after it as well. (Despite horrific, unacceptably bad coding style shown in your sample. I hope it's only for example).

The only problem is how you tried to use it. System.String.Join expects second parameter of very different type, string[]. But this little problem has nothing to do with your question. I don't even know why would you need asking it; you could easily validate your code if you did something legitimate with your Stment object. Besides, simple logic should tell you that this is quite legitimate thing.

—SA
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

Whatever you do, I suggest you test whether the result of the 'switch statement gave a valid result before executing any code that depends on a valid result::
int[] Stment = null;

switch (level)
{
    case 5:
        Stment = new int[] {5, 10, 15, 20};
        break;
    case 50:
        Stment = new int[] {50, 60, 70, 80};
        break;
}

if (Stment == null)
{
    // throw an error ?
}
else
{
    string disp = string.Join(Environment.NewLine, Stment);
    MessageBox.Show(disp);
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100