collection and property initializers are so nice

I happened to change a piece of code over the weekend and used both.  It's a tiny piece of code, so I thought it would make a good example of just how much readable code is using them.

Before:

 List<Property> p = new List<Property>(1);
Property pr = new Property();
pr.Name = "Description";
pr.Value = Description;
p.Add(pr);

After:

 List<Property> properties = new List<Property>()
{
    new Property() { Name = "Description", Value = Description },
};

Ah, much nicer.  (Yes, technically the second doesn't get the list size set to 1 like the first does, but I consider that a micro-optimization in the first place).

Remember, focus on making code easier to *read*, not easier to write.  That's one of the reasons I don't use "var" above, even though it causes a DRY failure - I like not having to read past the "=" to get the type.  Also, I like not having some locals that have the type out front and some that don't.  However, that's really for a different post, so nevermind. :)

Comments