tags:

views:

62

answers:

3

I have something like this:

[Description("Sets the color."),
Category("Values"),
DefaultValue(Color.White),
Browsable(true)]
public Color MyColor
{
    get
    {
        return myColor;
    }
    set
    {
        myColor = value;
    }
}
private Color myColor = Color.White;

I'm getting an error at this line:

DefaultValue(Color.White),

If the value is a boolean there isn't a problem, but when trying to set it to a color I get: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Can anyone identify the problem?

+5  A: 

Color.White isn't a constant expression; it rather is a readonly field static property1 and involves instantiation.

Edit:

For your information, an alternative way to set a Color's default value might look like this:

[DefaultValue(typeof(Color), "White"]
public Color MyColor
{ ... }

1. Ed Swangren pointed this out in his answer

Bryan Menard
A: 

The error description says it all :) Try to put there the color value as string (mean 'constant expression').

PS. in your code there is a default value set to the private member, so you can skip this attribute.

twk
+2  A: 

Because the predefined color objects in the Color struct are not constants, they are static properties with only a get accessor.

public static Color Transparent { get; }

That line actually return a new Color object by using the values in the KnownColor enum to construct it:

public static Color Transparent 
{ 
    get { return new Color( KnownColor.Transparent ); } 
}

So, as you can see, there is nothing constant about calling that method, which is why you receive an error.

Ed Swangren