How can this be optimized and brought to normal?

public void NewGenerating() { Generating = Random.Range(1, 5); if (Generating == 1) { } if (Generating == 2) { } if (Generating == 3) { } if (Generating == 4) { } if (Generating == 5) { } } 
  • switch (7 characters needed ...) - Igor
  • and what is wrong with normal now? - Grundy

1 answer 1

Conventional branching using a conditional operator is not shameful. As long as the branches do not contain nested instructions, the code block may look unnecessarily bloated, but it will cease to be so when the conditions are implemented.

C # also allows branching with a switch . However, it should be understood that expressions in all case must be of the same type.

 public void NewGenerating() { Random r = new Random(); switch (r.Next(1, 5)) { case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; } } 

You can also use the Dictionary(int, Action) value dictionary. The key is the generated number, and the value is a function with instructions that is later called.

 public void NewGenerating() { Dictionary<int, Action> vars = new Dictionary<int, Action>(); vars.Add(1, () => { /*Console.WriteLine("1 was generated");*/ }); vars.Add(2, () => { }); vars.Add(3, () => { }); vars.Add(4, () => { }); vars.Add(5, () => { }); Random r = new Random(); Action ac = vars[r.Next(1, 5)]; ac(); } 
  • Thanks for the help :) - Isyuko