C # 4.0: Is it possible to use color as an optional parameter with a default value?

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

This leads to the error that c must be a compile time constant. I read a little about this, and most examples deal with strings and ints. I realized that I can use the colorconverter class, but I'm not sure if it will be very efficient. Is there a way to just pass the base 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); } 
+41
c # optional-parameters
May 10 '10 at 16:27
source share
4 answers

I came across this, and the only workaround I found was to use nullables.

 public void log(String msg, Color? c = null) { loggerText.ForeColor = c ?? Color.Black; loggerText.AppendText("\n" + msg); } 

Another possible syntax:

 loggerText.ForeColor = c.GetValueOrDefault(Color.Black); 
+80
May 10 '10 at 16:29
source share

You can check if Color is Color.Empty (default value: default(Color) ) or use a value with a null value and check the null value.

 public void log(String msg, Color? c = null) { ... } 
+8
May 10 '10 at 16:29
source share

Do not indicate color. Instead, indicate “error level” and map between each error level and color value. Thus, 0 and below can be black, then 1 = amber,> 2 = red. No need to worry about default values ​​and / or not specify a value.

+3
May 10 '10 at 16:35
source share

Using:

 public GraphicsLine(Point startPoint, Point endPoint, Color? color = null, double width = 1.0) { StartPoint = startPoint; EndPoint = endPoint; Color = color ?? Colors.Black; Width = width; } 
0
Feb 19 '13 at 15:43
source share



All Articles