How can I set the DefaultValue property of a list property?

I have a Helper class as such:

class Helper : Settings
{
    [Setting, DefaultValue(false)]
    public bool DeclineData { get; set; }

    // ....

    [Setting, DefaultValue(new List<string>())]
    public List<string> AcceptList { get; set; }
}

      

However, mine DefaultValue

for List<string>

results in an error:

The attribute argument must be a constant expression, a typeof expression, or an array creation expression of the attribute parameter type

I also tried typeof(List<string>)

, which also failed.

Setting

in fact System.Attribute

, since it Settings

inherits from it, it is not my call as its not my code or open to change.

My question is, how do I set DefaultValue

to my property AcceptList

?


While Selman22's answer does not create a direct error for setting the default, it does not allow data to be serialized or deserialized, and since I am very limited in information about this obfuscated API, I followed a different route.

This is not a direct solution, but rather a workaround until I figure out more information about this API by setting mine DefaultValue("")

to empty and using my property as a delimited string to convert back and forth from string to list privately I was able to save the data I needed ...

+3


source to share


2 answers


Since it must be a compile-time constant, you can only set it to null:



[Setting, DefaultValue(default(List<string>)]
public List<string> AcceptList { get; set; }

      

+1


source


You can set default values ​​for properties in the constructor.



class Helper : Settings
{
    public Helper()
    {
       DeclineData = false;
       AcceptList = new List<string>();
    }
    public bool DeclineData { get; set; }
    public List<string> AcceptList { get; set; }
}

      

+1


source







All Articles