Search code examples
c#xmljsoncustom-attributes

How can I accept a 'dictionary' of data as a custom .NET attribute parameter?


I recently discovered that a .NET attribute can only contain primitive types, strings, enums, objects, and single parameter arrays of these types as discussed here.

I have the need to accept an IDictionary<string, string> through a .NET attribute, but obviously I can't use IDictionary<string, string> for the above reason. So, I am here looking for alternatives that can work within these guidelines.

// I want to do this, but can't because of the CLR limitation
[MyAttribute(Attributes = new Dictionary { { "visibility", "Condition1" }, { "myAttribute", "some-value" } })]

Two possible options I came up with are to use XML or JSON in the declaration (as a string on the .NET attribute), which can be easily serialized into IDictionary<string, string> for my application, but this turns the declaration into a lengthy error-prone string with no syntax checking.

// XML
[MyAttribute(Attributes = "<items><item key='visibility' value='Condition1'/><item key='myAttribute' value='some-value'/></items>")]

// JSON
[MyAttribute(Attributes = "{ 'visibility': 'Condition1', 'myAttribute': 'some-value' }")]

What, if any, other alternatives are available that are more elegant/straightforward than this?


Solution

  • As far as I know, you can add an attribute several times (Edit: If you set AllowMultiple to true, as Robert Levy noted). So maybe instead of using one attribute with a whole dictionary, you could use several attributes, one for each dictionary entry, each with a key and a value parameter.

    [MyDictionaryEntry(Key = key1, Value = val1)]
    [MyDictionaryEntry(Key = key2, Value = val2)]
    [MyDictionaryEntry(Key = key3, Value = val3)]
    [MyDictionaryEntry(Key = key4, Value = val4)]