Click here to Skip to main content
15,891,981 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
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:

C#
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

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.
 
Share this answer
 
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
 
Share this answer
 
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::
C#
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);
}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900