Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 4.0: Can I use a Color as an optional parameter with a default value? [duplicate]

    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);     } 
like image 456
DTown Avatar asked May 10 '10 16:05

DTown


1 Answers

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); 
like image 169
scobi Avatar answered Oct 27 '22 00:10

scobi