Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 452
NightOwl888 Avatar asked Jan 21 '14 17:01

NightOwl888


People also ask

How can you specify target for custom attribute?

Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.


1 Answers

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)]
like image 50
Sebastian Negraszus Avatar answered Oct 31 '22 14:10

Sebastian Negraszus