74
    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);
    }
DTown
  • 2,132
  • 2
  • 20
  • 29

4 Answers4

143

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 ?? Color.Black;
    loggerText.AppendText("\n" + msg);
}

Other possible syntax is:

loggerText.ForeColor = c.GetValueOrDefault(Color.Black);
Paul
  • 25,812
  • 38
  • 124
  • 247
scobi
  • 14,252
  • 13
  • 80
  • 114
9

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
  • 9,255
  • 4
  • 37
  • 54
4

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
  • 41,080
  • 29
  • 148
  • 220
  • +1 Emphasize the what, not the how. – Bryan Watts May 10 '10 at 16:38
  • 5
    Completely disagree - apart from not answering the question, this introduces a new semantic "error level" which then makes this method less useful across different applications (what if I want warnings to be orange in one application and yellow in another). – Justicle Sep 25 '11 at 21:52
  • @Justicle I see what you're saying, but the actual color should be a presentation concern, and this way the *semantics* are the same in every app, even though the presentation of each app might be different (column in a logfile, colour of a UI element, send an email or don't etc). – Neil Barnwell Aug 25 '15 at 13:41
2

Usage suggestion:

public GraphicsLine(Point startPoint, Point endPoint, Color? color = null, double width = 1.0)
{
    StartPoint = startPoint;
    EndPoint = endPoint;
    Color = color ?? Colors.Black;
    Width = width;
}
Eric Ouellet
  • 10,996
  • 11
  • 84
  • 119