Building a set of “constant” objects

I've got a class that returns a Button, setting the colors in the constructor:

public class Button { public Button(string text, Color background, Color textColor, Color shadow) { Button.Text = text; Button.BackgroundColor = background; Button.TextColor = textColor; Button.Shadow = shadow; } } 

The buttons get new'd up at various points, and there can be many present and alive for some time.

I need to support multiple fixed color palettes. I'm hoping to do something a little smarter than a bunch of constructor calls.

A usage that seems clean would be to enable passing in the text and the palette you want. Something like:

Button button = new Button("Go", ColorPalette.Bright); Button button2 = new Button("Stop", ColorPalette.Blues); 

It's a bit over my rusty head and I'd really appreciate some thoughts.

I'm thinking of a structure like this:

public struct ColorPalette { public Color Background { get; set; } public Color TextColor { get; set; } public Color Shadow { get; set; } } 

And then static instances – these are the "constant" objects, for lack of a better characterization:

public class Button { private static readonly ColorPalette bright = new ColorPalette { Background = Color.Yellow, TextColor = Color.Black, Shadow = Color.Green }; private static readonly ColorPalette blues = new ColorPalette { Background = Color.Blue, TextColor = Color.White, Shadow = Color.LightBlue}; 

The constructor would take in an enum that I'd map to the chosen palette, and set colors from the matching ColorPalette variable declared above.

 public Button(string text, ColorPalettes palette) { ColorPalette myPalette; //overly simplified here if (palette = ColorPalettes.Bright) myPalette = bright; ... Button.Text = text; Button.BackgroundColor = myPalette.Background; Button.TextColor = myPalette.TextColor; Button.Shadow = myPalette.Shadow; } 

Does this seem reasonable? I see myself winding up with many ColorPalette variables every time I create a Button, which seems wasteful. The enum to ColorPalette variable also seems clunky.

Thanks in advance for your time and thoughts.

by ice1288 via /r/csharp

Leave a Reply