HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Change the background color of the console with the help of enum

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thebackgroundwithenumcolorhelpconsolechange

Problem

I've recently learned the concept of enum and method calling with the enum. From what I learned I've done this simple snippet which changes the background color of the console with the help of enum and method.

public static void SetColor(RanngDe R){
        switch (R){
            case RanngDe.Blue:
                 Console.BackgroundColor = ConsoleColor.Blue;
                 break;

            case RanngDe.Green:
                 Console.BackgroundColor = ConsoleColor.Green;
                 break;
            default:
                 Console.BackgroundColor = ConsoleColor.Yellow;
                 break;
        }   
    }

// Enum Declaration
public enum RanngDe{
    Blue=0,
    Green=1,
    Yellow=3
}


I'm calling RanngDe method in the main method in switch ...case block as menu driven. I know, I've used switch ...case in void SetColor(RanngDe R) method, which is my major concern, because this makes my code redundant as I'm calling it in the menu driven program.

Is this approach acceptable as good practice? If not then, how should I make this better?

Solution

As has been mentioned using a Dictionary will make your code much simpler:

public enum RanngDe
{
    Blue = 0,
    Green = 1,
    Yellow = 3
}
static Dictionary colors = new Dictionary()
{
    {RanngDe.Blue,ConsoleColor.Blue },
    {RanngDe.Green,ConsoleColor.Green },
    {RanngDe.Yellow,ConsoleColor.Yellow }
};
public static void SetColor(RanngDe R)
{
    Console.BackgroundColor = colors[R];
}


Depending on your implementation you might be able to do away with the method completely and just use the assignment.

I came up with another approach. If you change the values of Ranngde to be the same as the ConsoleColor enum, you can cast the Ranngde value to ConsoleColor:

public enum RanngDe
{
    Blue = ConsoleColor.Blue,
    Green = ConsoleColor.Green,
    Yellow = ConsoleColor.Yellow
}
public static void SetColor(RanngDe R)
{
    Console.BackgroundColor = (ConsoleColor)R;
}

Code Snippets

public enum RanngDe
{
    Blue = 0,
    Green = 1,
    Yellow = 3
}
static Dictionary<RanngDe, ConsoleColor> colors = new Dictionary<RanngDe, ConsoleColor>()
{
    {RanngDe.Blue,ConsoleColor.Blue },
    {RanngDe.Green,ConsoleColor.Green },
    {RanngDe.Yellow,ConsoleColor.Yellow }
};
public static void SetColor(RanngDe R)
{
    Console.BackgroundColor = colors[R];
}
public enum RanngDe
{
    Blue = ConsoleColor.Blue,
    Green = ConsoleColor.Green,
    Yellow = ConsoleColor.Yellow
}
public static void SetColor(RanngDe R)
{
    Console.BackgroundColor = (ConsoleColor)R;
}

Context

StackExchange Code Review Q#161789, answer score: 6

Revisions (0)

No revisions yet.