rltcounter221 rltcounter221 - 2 months ago 5
C# Question

How can I make loop instead of switch statement?

How can I write this shorter? For each case I have to write this and then It is too long because there are 48 numbers so I need 48 cases. Is there a way to make a loop?

switch (ballBounce.ToString())
{
case "1":
if (ballBounce == n0)
{
textBox1.Text = number.ToString();
}
break;

case "2":
if (ballBounce == n1)
{
textBox1.Text = number.ToString();
}
break;

case "3":
if (ballBounce == n2)
{
textBox1.Text = number.ToString();
}
break; ...

Answer

The loop is useless in this case. You can use dictionary.

private Dictinoary<string, string> cases = new Dictionary<string, string> {
  {"1", "one"},
  {"2", "two"},
  // ...
};

// in some method
string text;
if (cases.TryGetValue(ballBounce.ToString(), out text)){
   this.textBox1.Text = text;
}

If you want something smarter than simple value, you can have functions in the dictionary.

private Dictinoary<string, Func<string>> cases = new Dictionary<string, Func<string>> {
  {"1", () => "one"},
  {"2", () =>
    {
      if (DateTime.Now.Seconds % 2 == 0) { return "A"; }
      else { return "B"; }
    }},
  // ...
};

// in some method
Func<string> textProvider;
if (cases.TryGetValue(ballBounce.ToString(), out textProvider)){
   this.textBox1.Text = textProvider();
}
Comments