Search code examples
c#refactoring

How to Refactor this if condition


Is there a better way to refactor this if condition? or just leave it alone?

if (buttonindex == 1 || buttonindex == 4 || buttonindex == 10 || buttonindex == 12 || buttonindex == 14 || buttonindex == 15 || buttonindex == 17|| buttonindex == 18) 
{
 dosomething();
}

Solution

  • You could declare an array with the valid indexes like

    int[] validIndexes = new int[] { 1, 4, 10, 12, 14, 15, 17, 18 };

    And then use it like this

    if (validIndexes.Contains(buttonindex))
    {
        dosomething();
    }