system
Given the following post, respond as if you're commenting on Reddit:
human
Reducing if, if-else statements possible on c#?

Hi,

I am working on my own project in c# and during this quest of learning I was wondering if there is a way to avoid using too many if statements. I've read that you could use OOP, but nothing that I've seen seems to be coherent for me to understand. For example, I have this code... and I want to find a way to not have to keep adding if statements in case I add another state to my light.  
I would like some ideas, there's nothing to solve here lol :)

    public void checkColor(string color, int state)
            {
                if (color == "r" && state == 1)
                {
                    redState = lampOn;
                }
                else if (color == "r" && state == 2)
                {
                    redState = lampBlink;
                }
                else if (color == "y" && state == 1)
                {
                    yellowState = lampOn;
                }
                else if (color == "y" && state == 2)
                {
                    yellowState = lampBlink;
                }
                else if (color == "g" && state == 1)
                {
                    greenState = lampOn;
                }
                else if (color == "g" && state == 2)
                {
                    greenState = lampBlink;
                }
                else if (color == "b" && state == 1)
                {
                    blueState = lampOn;
                }
                else if (color == "b" && state == 2)
                {
                    blueState = lampBlink;
                }
    
            }

Thanks!
gpt
you could separate the two checks as a start ...

    var tmp;
    switch(state)
      case 1: tmp= lampOn
      case 2: tmp= lampBlink

    switch(color)
      case 'r': redState = tmp
      case 'g': greenState = tmp
      case 'b': blueState = tmp
    
Though really the first question to me is why you got an int-state coming into the function, and then a lampOn/lampBlink state (which seems to come from variables) and not just a LampState-Enum that is used in both places.