I know I have a fundamental problem, I do not fully understand List objects.

Based on a user input from a list box I want to creat a different list named icons.
I previously had issues with the switch function, seemed I was doing it at the class level, so I am trying to put it in the following method. The error I get is a local variable named "icons" is already defined in this scope.
I tried creating the list object outside the method, and I'm either not getting the syntax correct to assign within the switch or I am barking up the wrong tree.
Thanks in advanced for putting up with my remedial C# !!

 string board = "1";

 private void SelectBoard()
        {

            // Each of these letters is an interesting icon 
            // in the Webdings font, 
            // and each icon appears twice in this list
            switch (board)
            {
                case "1":
                    List<string> icons = new List<string>()
               { 
        "!", "!", "N", "N", ",", ",", "k", "k",
        "b", "b", "v", "v", "w", "w", "z", "z" 
               };
                    break;

                case "2":
                    List<string> icons = new List<string>()
              {
                 //another list of 8*2 char
              };
                    break;

                case "3":
                    List<string> icons = new List<string>()
               {
                  //another list of 8*2 char
               };
                    break;

                case "4":
                    List<string> icons = new List<string>()
               {
                  //another list of 8*2 char
               };
                    break;

                case "5":
                    List<string> icons = new List<string>()
               {
                  //another list of 8*2 char
               };
                    break;

                case "6":
                    List<string> icons = new List<string>()
               {
                    //another list of 8*2 char
               };
                    break;
            }
        }

Edited 3 Years Ago by Triryche

You almost had it and had the correct idea moving the list declaration outside of the switch function, the small details are what caught you out though!

string board = "1";

// Here we declare an empty list called icons
List<string> icons = new List<string>();

switch (board)
{
    // We then re-initialise the list depending upon case
    case "1":
        icons = new List<string>() { "!", "!", "N", "N", ",", ",", "k", "k", "b", "b", "v", "v", "w", "w", "z", "z" };
            break;
    case "2":
        icons = new List<string>() { [Different String Set Here] };
            break;  
}

In the above code we declare the icon list once outside of the switch statement;

Within each case statement we simply re-instanciate the list with a new value set instead of fully re-defining it each time which was the original cause of the error.

Edited 3 Years Ago by Mike Askew

now I get the error Cannot use local variable 'icons' before it is declared

with the following code:

 private void SelectBoard()
        {
            string board = "1";
             List<string> icons = new List<string>();
            // Each of these letters is an interesting icon 
            // in the Webdings font, 
            // and each icon appears twice in this list
            switch (board)
            {
                case "1":
                    icons = new List<string>()                                       
               {"!", "!", "N", "N", ",", ",", "k", "k",
        "b", "b", "v", "v", "w", "w", "z", "z" ;

               break;

               ...

The basic code should work, especially after you put in the missing brace on line 13.

I would add one thing though, if you want to use icons somewhere else, you should either return it from the method or declare it at class level.

If re-instantiating gives you problems you could use the Clear and AddRange method instead:

        icons.Clear();
        icons.AddRange(new string[]
                {
                "!", "!", "N", "N", ",", ",", "k", "k",
                "b", "b", "v", "v", "w", "w", "z", "z"
                });

Could you highlight which line the error occurs on, Tinstaafl is correct about the alternate way to change the value also though :)

I find it odd that you would get an object not initialised error in the code block you linked as it is specifically initialised on line 4 to be a new empty list.

I get a red squiggly for icons starting at line 79 and for all 'icons' in the switch with the following code. The same is true when trying:

     icons.Clear();
    icons.AddRange(new string[]
    {
    "!", "!", "N", "N", ",", ",", "k", "k",
    "b", "b", "v", "v", "w", "w", "z", "z"
    });

This is the code I have so far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;

namespace MatchGame
{
    public partial class Form1 : Form
    {

        SoundPlayer flip = new SoundPlayer(MatchGame.Properties.Resources.flip);
        SoundPlayer match = new SoundPlayer(MatchGame.Properties.Resources.chimes);
        SoundPlayer noMatch = new SoundPlayer(MatchGame.Properties.Resources.noMatch);
        SoundPlayer win = new SoundPlayer(MatchGame.Properties.Resources.tada);

        string board = "1";
        List<string> icons = new List<string>();

        // firstClicked points to the first Label control  
        // that the player clicks, but it will be null  
        // if the player hasn't clicked a label yet
        Label firstClicked = null;

        // secondClicked points to the second Label control  
        // that the player clicks
        Label secondClicked = null;

        // Use this Random object to choose random icons for the squares
        Random random = new Random();

        /// <summary> 
        /// Check every icon to see if it is matched, by  
        /// comparing its foreground color to its background color.  
        /// If all of the icons are matched, the player wins 
        /// </summary> 
        private void CheckForWinner()
        {
            // Go through all of the labels in the TableLayoutPanel,  
            // checking each one to see if its icon is matched 
            foreach (Control control in tableLayoutPanel1.Controls)
            {
                Label iconLabel = control as Label;

                if (iconLabel != null)
                {
                    if (iconLabel.ForeColor == iconLabel.BackColor)
                        return;
                }
            }
            // If the loop didn’t return, it didn't find 
            // any unmatched icons 
            // That means the user won. Show a message and close the form
            win.Play();
            MessageBox.Show("You matched all the icons!", "Congratulations");
            Close();
        }


        /// <summary> 
        /// Select a playing cards based on user input.
        /// </summary> 
        private void SelectBoard()
        {
            // Each of these letters is an interesting icon 
            // in the Webdings font, 
            // and each icon appears twice in this list

            board = comboBox1.ToString();

            switch (board)
            {
                case "1":
                    icons = new List<string>()                                       
               {  
        "!", "!", "N", "N", ",", ",", "k", "k",
        "b", "b", "v", "v", "w", "w", "z", "z" 
               };
                    break;

                case "2":
                    icons = new List<string>()
              { // another list};
                    break;

                case "3":
                    icons = new List<string>()
                { // another list};
                    break;

                case "4":
                    icons = new List<string>()
               { // another list};
                    break;

                case "5":
                     icons = new List<string>()
                { // another list};
                    break;

                case "6":
                   icons = new List<string>()
                { // another list};
                    break;
            }
        }


        /// <summary> 
        /// Assign each icon from the list of icons to a random square 
        /// </summary> 
        private void AssignIconsToSquares()
        {

            // The TableLayoutPanel has 16 labels, 
            // and the icon list has 16 icons, 
            // so an icon is pulled at random from the list 
            // and added to each label 
            foreach (Control control in tableLayoutPanel1.Controls)
            {
                Label iconLabel = control as Label;
                if (iconLabel != null)
                {
                    int randomNumber = random.Next(icons.Count);
                    iconLabel.Text = icons[randomNumber];
                    iconLabel.ForeColor = iconLabel.BackColor;
                    icons.RemoveAt(randomNumber);
                }
            }

        }
        public Form1()
        {
            InitializeComponent();
            AssignIconsToSquares();
        }

        /// <summary> 
        /// Every label's Click event is handled by this event handler 
        /// </summary> 
        /// <param name="sender">The label that was clicked</param>
        /// <param name="e"></param>
        private void label_Click(object sender, EventArgs e)
        {
            // The timer is only on after two non-matching  
            // icons have been shown to the player,  
            // so ignore any clicks if the timer is running 
            if (timer1.Enabled == true)
                return;

            Label clickedLabel = sender as Label;

            if (clickedLabel != null)
            {
                // If the clicked label is black, the player clicked 
                // an icon that's already been revealed -- 
                // ignore the click 
                if (clickedLabel.ForeColor == Color.Black)
                    return;

                if (firstClicked == null)
                {
                    flip.Play();
                    firstClicked = clickedLabel;
                    firstClicked.ForeColor = Color.Black;

                    return;
                }
                // If the player gets this far, the timer isn't 
                // running and firstClicked isn't null, 
                // so this must be the second icon the player clicked 
                // Set its color to black

                secondClicked = clickedLabel;
                secondClicked.ForeColor = Color.Black;
                this.Refresh();
                flip.PlaySync();
                //System.Threading.Thread.Sleep(750);

                CheckForWinner();

                // If the player clicked two matching icons, keep them  
                // black and reset firstClicked and secondClicked  
                // so the player can click another icon 
                if (firstClicked.Text == secondClicked.Text)
                {
                    //System.Threading.Thread.Sleep(750);

                    firstClicked = null;
                    secondClicked = null;
                    match.PlaySync();
                    return;
                }

                // If the player gets this far, the player  
                // clicked two different icons, so start the  
                // timer (which will wait three quarters of  
                // a second, and then hide the icons)    
                timer1.Start();
            }
        }
        /// <summary> 
        /// This timer is started when the player clicks  
        /// two icons that don't match, 
        /// so it counts three quarters of a second  
        /// and then turns itself off and hides both icons 
        /// </summary> 
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            // Stop the timer
            timer1.Stop();

            // Hide both icons
            noMatch.Play();
            firstClicked.ForeColor = firstClicked.BackColor;
            secondClicked.ForeColor = secondClicked.BackColor;

            // Reset firstClicked and secondClicked  
            // so the next time a label is 
            // clicked, the program knows it's the first click
            firstClicked = null;
            secondClicked = null;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SelectBoard();
        }
    }
}

Edited 3 Years Ago by Triryche: fix typo in code snippet

The erroe is longer now
Cannot use local variable 'icons' before it is declared. The declaration of the local variable hides the field 'MatchGame.Form1.icons'

Can you upload your solution somewhere for me to download and look at? Can't see what would cause the error by eye.

Well I saved everything and rebooted the computer, and that error went away.
I have a new unhandled exceptoin that I will try to puzzle out.

Thanks again for all your help!!

Edited 3 Years Ago by Triryche

When I copy and paste your code into a new form, I get no errors related to icons. Check to see if it's declared at the same level in a different file.

On a side note, { // another list}; confuses Visual Studio and things won't format properly. Use

                { // another list
                };

Edited 3 Years Ago by tinstaafl

On a side note, { // another list}; confuses Visual Studio and things won't format properly.

That's actually how I have it in my code.
That was copy/paste-itis

I did get the program to work correctly after rebooting the pc. And I cleaned and rebuilt several times prior. I had a computational intense program running while I was tinkkering, maybe it was a mem leak?
After the 'icons' issue I had a problem with a null coming from comboBox1 which was corrected by adding a default text.

Thanks again for all your help!!

This question has already been answered. Start a new discussion instead.