4

I want to initialize WebControl objects, inline, but for some fields this is a little bit tricky. For instance when I try to initialize the Attributes property of a TextBox object like this:

using System.Web.UI.WebControls;
Panel panel = new Panel() { Controls = { new TextBox() { Attributes = { { "key", "value" } } } } };

I get the error:

Cannot initialize type 'AttributeCollection' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

Any idea how could inline initialization work in this case ?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Chris
  • 1,213
  • 1
  • 21
  • 38
  • Your question sounds similar to [this one](http://stackoverflow.com/questions/30668572/htmlgenericcontrol-attributes-in-object-initializer), and the accepted answer says that it's not possible. – Frank Tan Jul 29 '16 at 19:59

1 Answers1

5

You can do this but if you use C#6. This is called index initialization so try the following code but as I said this should works fine in Visual Studio 2015 and C#6:

Panel panel = new Panel
{
    Controls =
    {
        new TextBox
        {
            Attributes =
            {
                ["readonly"] = "true",
                ["value"] = "Hi"
            }
        }
    }
}; 

The old collection initializers (Prior to C#6) only works with types that implement IEnumerable<T> and have an Add method. But now any type with an indexer will allow initialization via this syntax.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109