I'm starting a small project in WinForms C# and have something like this:
UserControl uc1 = new UserControl();
UserControl uc2 = new UserControl();
mainPanel.Controls.Add(uc1);
mainPanel.Controls.Add(uc2);
Console.WriteLine(mainPanel.Controls["UserControl"].Width);
Knowing that mainPanel.Controls
is a collection, how come that UserControl - class name of uc1
and uc2
- can act like an index?
And if so, these 2 elements in the collection have the same index, namely UserControl, is this even possible? Or this is something particular of .NET Framework?
It's possible in this collection
If you take a look at the source code for the ControlCollection you'll see the indexer that takes a string:
Controls are kept in an (Array)list and IndexOfKey is used to find the first index of the given name:
There isn't any uniqueness constraint in this code.. it's just "find the first added one with that string"
Side note; it's interesting to look at such old code (ArrayList) and consider how it might be written now that we have more powerful collections, LINQ, dictionaries, named parameters.. clearly an optimization there that MS expect people to repeatedly use string lookup, in loops etc, so they keep the last used string and compare this string to see.. Whicj in turn I guess means that for best resource use if you know you're cmgoing to repeatedly access a control by the same string (in a loop?) access it by number index instead..