1

I'm starting learning C# a couple days, sr if it's stupid question! I had a string array like this

private readonly string[] algorithm_list = {
                                              "Genetic Algorithm",
                                              "Dynamic Algorithm"
                                          };

and my code

switch (al_choose)
            {
                case algorithm_list[0]:
                    break;
                case algorithm_list[1]:
                    break;
                default:

            }

The error is algorithm_list[0] is not a constant! So I try other declaration like

private readonly string[] algorithm_list 

or

private contant string[] algorithm_list

But it still doesn't work???? So, any suggestion for me? thanks so much!

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
duykhoa
  • 2,227
  • 1
  • 25
  • 43
  • Duplicate: [switch case in c# - a constant value is expected](http://stackoverflow.com/questions/7593377/switch-case-in-c-sharp-a-constant-value-is-expected) – Alina B. Mar 30 '13 at 05:19
  • no, it's different, because I want to make this to a list item in view, and also use it again in code behind, so, this is the thing I considered – duykhoa Mar 30 '13 at 08:04

2 Answers2

7

For these cases, its better to use Enum

public enum AlgorithmList
{
        GeneticAlgorithm,
        DynamicAlgorithm
}

Then:

switch (al_choose)
{
    case AlgorithmList.GeneticAlgorithm:
        break;
    case AlgorithmList.DynamicAlgorithm:
        break;
    default:
        break;
}

EDIT If you are going to bind the values of the Enum to a ComboBox you can do it this way:

yourCombobox.ItemsSource = Enum.GetValues(typeof(AlgorithmList)).Cast<AlgorithmList>();
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
  • Thanks for your help, but it still has a problem here, I had a combo box in view, this load Algorithm List as an item list, and it didn't accept enum type. – duykhoa Mar 30 '13 at 08:00
4

Array elements are not constants so you can't use array elements in switch statement.

Options:

  • replace usage of array elements with inline constant case "Genetic Algorithm":... or actual constant values const string Choice1="Genetic Algorithm";... case Choice1:...
  • use sequence of if statements: if (al_choose == algorithm_list[0]) { /*do something*/ }
  • standard approach for such switch statement is dictionary of "choice" to "Action delegate", but I'd not jump into that.
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179