Guapo
Guapo

Reputation: 3482

How do I set a DefaultValue 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 my DefaultValue for List<string> results in error:

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

I've also tried typeof(List<string>) which also failed.

Setting is actually System.Attribute as Settings inherits from it, that's not my call as its not my code or open to changes.

My question is, how can I set a DefaultValue to my property AcceptList?


While Selman22 answer does not generate a direct error to set the default value, it doesn't let it serialize or deserialize the data and since I am very limited in the information about this obfuscatated API I followed a different route.

This is not a direct solution but rather an workaround until I figure out more information about this API, by setting my DefaultValue("") to empty and using my property as string with a delimiter to convert back and forth from a string to a list within a private property I was able to save the data I needed to.

Upvotes: 7

Views: 12749

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

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

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

Upvotes: 3

Magnus
Magnus

Reputation: 46977

You can set default values of the 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; }
}

Upvotes: 1

Related Questions