Wednesday, December 24, 2008

C# Collection Initializer

A co-worker sent me this code change... nice.

Code to add items to a generic list:
_graphBackdrops = new List();

_graphBackdrops.Add(new Backdrop(Color.BlueViolet));
_graphBackdrops.Add(new Backdrop(Color.DarkSeaGreen));
_graphBackdrops.Add(new Backdrop(Color.DarkTurquoise));
_graphBackdrops.Add(new Backdrop(Color.Purple));
_graphBackdrops.Add(new Backdrop(Color.RoyalBlue));

Code to add items to a generic list, using a collection initializer:
_graphBackdrops = new List
new Backdrop(Color.BlueViolet),
new Backdrop(Color.DarkSeaGreen),
new Backdrop(Color.DarkTurquoise),
new Backdrop(Color.RoyalBlue)

-Thanks to Johannes!

If you want to take it a step further, you can also use object initalizers, like in this example from MSDN:
List cats = new List
new Cat(){ Name="Sylvester", Age=8 },
new Cat(){ Name="Whiskers", Age=2},
new Cat() { Name="Sasha", Age=14}

Note that you are setting the properties on the newly instantiated object, i.e. Name="Sylvester", Age=8

So rather than writing:
List cats = new List();
var cat = new Cat();
cat.Name = "Whiskers";
cat.Age = 2;

You can have:
List cats = new List
{new Cat(){ Name="Whiskers", Age=2}}

Much shorter, cleaner, and easier to maintain!

Object and Collection Initializers (C# Programming Guide)
Anonymous Types (C# Programming Guide)

No comments: