Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a DefaultValue of a list property?

Tags:

c#

.net

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.

like image 505
Guapo Avatar asked Nov 01 '22 11:11

Guapo


1 Answers

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; }
like image 104
Selman Genç Avatar answered Nov 15 '22 05:11

Selman Genç