2

I am trying to use the defaultvalue attribute Default Value Documentation

So I know how to do a default attribute with a string

 [DefaultValue("This is the message")]

But how do I do a default value for a dictionary ?

I tried this

   [DefaultValue(new Dictionary<string, string>() { { "Test", "test" } })]

but I get this error

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

Micah Armantrout
  • 6,781
  • 4
  • 40
  • 66
  • 1
    You can't. Attribute parameters have to be const expressions, and constructing an object isn't. There is no way to accomplish what you want if you have to use `DefaultValueAttribute`. – Lasse V. Karlsen Jul 13 '20 at 13:38
  • 1
    I am surprised [there is no good](https://www.google.com/search?q=Error+CS0182+An+attribute+argument+must+be+a+constant+expression,+typeof+expression+or+array+creation+expression+of+an+attribute+parameter+type+site:stackoverflow.com) canonical answer for this error. For what you need `DefaultValueAttribute` with dictionary as a value? Serialization? Certain control (winforms? wpf?)? Something else? – Sinatr Jul 13 '20 at 14:10
  • I want to give a default value for https://swagger.io/ – Micah Armantrout Jul 13 '20 at 14:13

1 Answers1

2

You can't use Dictionary in any attribute, but you can try to add your own attribute with key + value.

I don't know how do you want to use it, but I'd recommend trying something like:

public class DictionaryDefaultAttribute : DefaultValueAttribute
{
    public DictionaryDefaultAttribute(string key, string value) 
        : base(new Dictionary<string, string>() {{key, value}})
    {
    }
}
  • If you have a Dynamic Dictionary, the following code also worked for me. ``` [DefaultValue("{\"Field1\": \"Value1\",\"Field2\": \"Value2\",\"Field3\":\"Value3\"}")] [Required] public Dictionary Fields { get; set; }``` – tRuEsAtM Nov 14 '22 at 19:09