Question

hi I need dynamic array in attribute in c#

for example:

 public class MyHtmlAttributesAttribute : System.Attribute
 {
    private IDictionary<string, string> Attrib { get; set; }
    public MyHtmlAttributesAttribute()
    {
        Attrib = new Dictionary<string, string>();
    }
    public MyHtmlAttributesAttribute(params string[][] values)
        : this()
    {             
        foreach (var item in values)
        {
            if (item.Count() < 1)
                throw new Exception("bad length array");
            this.Attrib.Add(item[0].ToLower(), item[1]);
        }

    }
 }

but when I want use this attribute I get error : Array initializers can only be used in a variable or field initializer. Try using a new expression instead

I use this attribute by this style:

public class LoginViewModel
{

    [Required]
    [MyHtmlAttributes(new string[][]{{"Class", "ltr"}, {"AutoCompleteType" , "Disabled"}})]
    public string Email { get; set; }
  ...
  ..
 }

thank you for answer

Was it helpful?

Solution

The problem is not in the attribute in this case, but in the array initialization. {{"Class", "ltr"}, {"AutoCompleteType" , "Disabled"}} could be used in an array initializer, but not in a new[] expression. With new expression: new string[][] {new string[] { "Class", "ltr" }, new string[]{ "AutoCompleteType", "Disabled" } }; But since params is used, the encapsulating new string[] can be omitted:

 [MyHtmlAttributes(new string[]{"Class", "ltr"}, new string[]{"AutoCompleteType" , "Disabled"})]

The following is purely an alternative

An alternative is to allow multiple instances of the attribute to be applied, and combine them when obtaining them.

To allow multiple attributes:

[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
 public class MyHtmlAttributesAttribute : System.Attribute

Apply them as

    [MyHtmlAttributes("Class", "ltr")]
    [MyHtmlAttributes("AutoCompleteType", "Disabled")]
    public string Email { get; set; }

Of course the constructor and implementation of the attribute has to be altered to allow only a single attr-value pair, but adding/removing a pair should only be easier this way. Combining them by reading all the MyHtmlAttributes instances on a property should be straight forward enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top