views:

182

answers:

3
    public void log(String msg, Color c = Color.black)
    {
        loggerText.ForeColor = c;
        loggerText.AppendText("\n" + msg);

    }

This results in an error that c must be a compile-time constant. I've read up on this a little and most examples are dealing with strings and ints. I've figured out I can use the colorconverter class but I'm not sure it will be very efficient. Is there a way to just pass a basic color as an optional parameter?

    public void log(String msg, String c = "Black")
    {
        ColorConverter conv = new ColorConverter();
        Color color = (Color)conv.ConvertFromString(c);

        loggerText.ForeColor = color;
        loggerText.AppendText("\n" + msg);
    }
+8  A: 

I've run into this as well and the only workaround I've found is to use nullables.

public void log(String msg, Color? c = null)
{
    loggerText.ForeColor = c.HasValue ? c.Value : Color.Black;
    loggerText.AppendText("\n" + msg);
}
Scott Bilas
You can also use `default(Color)` as a default value - but sometimes this can make it impossible to differentiate a default value from a valid parameter value. Nullable tend to be better in this case.
LBushkin
@Bushkin: i totally agree with this!
Simon
+2  A: 

You could check if Color is Color.Empty (which is the default value: default(Color)) or use a nullable value and check for null.

public void log(String msg, Color? c = null) { ... }
Simon
+3  A: 

Don't specify the colour. Supply an "error level" instead, and have a mapping between each error level and a colour value. That way 0 and below could be black, then 1 = amber, >2 = red. No need to worry about default values and/or not specifying a value.

Neil Barnwell
+1 Emphasize the what, not the how.
Bryan Watts