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

Solution 1:

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);

Solution 2:

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) { ... }

Solution 3:

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.

Solution 4:

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;
}