norikoSD norikoSD - 1 month ago 6
C# Question

Color.Red cannot be a argument in Attribute

I have a cs class like this:

public class MyClass
{
[DefaultValue(Color.Red)]
public Color MyColor{get;set;}
}


The compiler always return error CS0182:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

What's wrong with me?

T_T

Answer

As has been noted, Color.Red is not a constant expression. If your intent is to work with something like PropertyGrid, then you can achieve this by adding ShouldSerialize* and Reset* methods:

public class MyClass
{
    public MyClass()
    {
        ResetMyColor();
    }
    public Color MyColor { get; set; }

    private bool ShouldSerializeMyColor() {  return MyColor != Color.Red; }
    private void ResetMyColor() { MyColor = Color.Red; }
}

If your intent is to work with XmlSerializer, then ShouldSerialize* must be public (the Reset* is not used by XmlSerializer):

public class MyClass
{
    public MyClass()
    {
        MyColor = Color.Red;
    }
    public Color MyColor { get; set; }

    public bool ShouldSerializeMyColor() {  return MyColor != Color.Red; }
}