-1

I'm having a problem here.

void Sre_Reconhecimento(object sender, SpeechRecognizedEventArgs e)
    {
        string text = System.IO.File.ReadAllText(@"C:\Users\ADMIN25\Desktop\testing.txt");
        string[] words = text.Split(',');
        switch (e.Result.Text)
        {

            case words[0]:
                MessageBox.Show("works!");
                break;
            case words[1]:
                MessageBox.Show("works too!");
                break;
        }

    }

When I'm trying to run the program, I get this error: A constant value is expected.

How can I fix it without using if/elseif case?

Amazing man
  • 35
  • 1
  • 7
  • 1
    No idea what you trying to achieve here... Clearly going for some amazing feat, but invalid code shown in the post does not convey it. Side note: you can't "debug" program that does not compile... – Alexei Levenkov Feb 18 '18 at 00:28
  • 2
    You can't. `switch` is used with constants only. If you only have variables, you have to use `if-else`. – Mark Benningfield Feb 18 '18 at 00:30
  • 1
    If you were truly amazing you would have read [ask], taken the [tour] and done [research](https://meta.stackoverflow.com/a/261593) before posting(which in this case simply means feeding the actual error message to Google - whew!) – Ňɏssa Pøngjǣrdenlarp Feb 18 '18 at 00:31
  • Take a look at `Array.IndexOf`. – skyoxZ Feb 18 '18 at 00:37

2 Answers2

6

You should do this with if / else.

However, if for some reason you really want to use a switch, you can sort of do it with pattern maching.

e.g.

void Main()
{
    string[] words = {"Foo", "Bar", "Quax"};
    var word = "Bar";

    switch(word)
    {
        case string w when w == words[0]:
            MessageBox.Show($"word was {words[0]}");
            break;
        case string w when w == words[1]:
            MessageBox.Show($"word was {words[1]}");
            break;
    }   
}

Really though, use if / else here. I don't think switch is appropriate for this type of use case.

Stuart
  • 3,949
  • 7
  • 29
  • 58
1

You cant use a switch statement dynamically like this, because its expects a constant value at compile time

However

  • You can use a collection of if statements,

  • You could also use a dictionary of Action

Exmaple

dict = new Dictionary<string, Action>()
        {
            {"Standard", CreateStudySummaryView},
            {"By Group", CreateStudySummaryByGroupView},
            {"By Group/Time", CreateViewGroupByHour}
        };

dict[value].Invoke();
TheGeneral
  • 79,002
  • 9
  • 103
  • 141