Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 530
Mike Webb Avatar asked Dec 15 '10 20:12

Mike Webb


1 Answers

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;    // ... } 
like image 189
Mr. TA Avatar answered Sep 18 '22 01:09

Mr. TA