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.
Do this:
void foo(... Color boxColor = default(Color)) { if(object.Equals(boxColor, default(Color))) boxColor = Color.Black; // ... } Quick aside: I like to use object.Equals static method because it's a consistent way to write an equality comparison. With reference types such as string, str.Equals("abc") can throw NRE, whereas string.Equals(str, "abc"[,StringComparison.___]) will not. Color is a value type and therefore will never be null, but it's better to be consistent in code style, especially at zero additional cost. Obviously this doesn't apply to primitives such as int and even DateTime, where == clearly states/communicates the mathematical equality comparison.
Or, with nullables (credit to Brian Ball's answer):
void foo(... Color? boxColor = null) { if(boxColor == null) boxColor = Color.Black; // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With