Reputation: 2302
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!
Upvotes: 1
Views: 1407
Reputation: 32481
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>();
Upvotes: 7
Reputation: 100547
Array elements are not constants so you can't use array elements in switch statement.
Options:
case "Genetic Algorithm":...
or actual constant values const string Choice1="Genetic Algorithm";... case Choice1:...
if
statements: if (al_choose == algorithm_list[0]) { /*do something*/ }
switch
statement is dictionary of "choice" to "Action delegate", but I'd not jump into that.Upvotes: 4