Search code examples
c#switch-statementcode-size

Simplify Switch Statement in following code


How can i make this code to be much smaller in size and more efficient :) ..?. I have made it so far, from a bigger old code, but i think it's still huge.

if (affix == Mod.Affix)
{
    Graphics.DrawText(text, textSize, position, Color.White);

    switch (levels)
    {
        case 1:
        {
            Size level = Graphics.DrawText(text, textSize, position, Color.Yellow);
            if (level != new Size()) 
            { 
                position.Y += level.Height; 
            }
        } break;

        case 2:
        {
            Size level = Graphics.DrawText(text, textSize, position, Color.Red);
            if (level != new Size()) 
            {
                position.Y += level.Height; 
            }
        } break;

        case 3:
        {
            Size level = Graphics.DrawText(text, textSize, position, Color.Green);
            if (level != new Size()) 
            { 
                position.Y += level.Height; 
            }
        } break;

        default:
            Size nextLevel = Graphics.DrawText(text, textSize, position, Color.Black);

            if (nextLevel != new Size()) 
            { 
                position.Y += nextLevel.Height;
            } 
        break;
    }
}

Thank you in advance!


Solution

  • Use a dictionary to map levels to colors:

    private static Dictionary<int, Color> levelColors = new Dictionary<int, Color>
    {
        { 1, Color.Yellow },
        { 2, Color.Red },
        { 3, Color.Green }
    };
    

    Then you can change your method to just be this:

    Color color;
    if (!levelColors.TryGetValue(levels, out color)) // try and get the color for the level
    {
        color = Color.Black; // Default to black if no level color found
    }
    
    Size level = Graphics.DrawText(text, textSize, position, color);
    if (level != new Size())
    {
        position.Y += level.Height;
    }
    

    That way, you don't need to modify the method as you add/alter level colors, you just update the dictionary.