Q:

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!

A:

Try something like this:
Color color = new Color();
switch (levels)
{
    case 1:
        color = Color.Yellow;
        break;

    case 2:
        color = Color.Red;
        break;

    case 3:
        color = Color.Green;
        break;

    default:
        color = Color.Black;
        break;
}
Size level = Graphics.DrawText(text, textSize, position, color);
if (level != new Size()) // ???
{ 
    position.Y += level.Height;
}

A:

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.

A:

You are doing the same code for each colour, try this:
switch (levels)
{
    case 1:
        AddHeight(Color.Yellow);
        break;
    case 2:
        AddHeight(Color.Red);
        break;
    case 3:
        AddHeight(Color.Green);
        break;
    default:
        AddHeight(Color.Black);
        break;
}

public void AddHeight(Color color){
    Size level = Graphics.DrawText(text, textSize, position, color);
    if (level != new Size()) // ???
    { 
        position.Y += level.Height;
    }
}

