Search code examples
c#parametersc#-4.0colorsdefault-value

Can I specify a default Color parameter in C# 4.0?


Here is an example function:

public void DrawSquare(int x, int y, Color boxColor = Color.Black)
{
    //Code to draw the square goes here 
}

The compiler keeps giving me the error: Default parameter value for 'boxColor'must be a compile-time constant

I have tried

Color.Black, 
Color.FromKnownColor(KnownColor.Black), and 
Color.FromArgb(0, 0, 0)

How do I make Color.Black be the default color? Also, I do not want to use a string Black to specify it (which I know would work). I want the Color.Black value.


Solution

  • Color.Black is a static, not a constant, so no, you cannot do this.

    To use a default, you can make the parameter nullable (Color?), and if it is null, then set it to Black.