Scott Guthrie is blogging with his usual enthusiasm about some new keystroke-saving language features we can all look forward to in the Orcas release of C#:
Object Initializers are great, and make it much easier to concisely add objects to collections. ...
Using the new Object Initializer feature alone (saves) 12 extra lines of code ... versus what I'd need to type with the C# 2.0 compiler.
The C# and VB "Orcas" compilers allow us to go even further, though, and also now support "collection initializers" that allow us to avoid having multiple Add statements, and save even further keystrokes: List<Person> people = new List<Person> {
new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 },
new Person { FirstName = "Bill", LastName = "Gates", Age = 50 },
new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
};
[from New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers ]
Fantastic! The next time I need to initialise a collection with a set of canned values, I can save valuable keypresses. And I do that sort of thing all the time: for instance, when I'm setting up data to demonstrate a LINQ query against... and... er... no, that's about it.
Almost every collection I code is populated procedurally, usually with a loop. I'm not knocking the object initialiser syntax, but the collection initialiser leaves me pretty cold. Where is the real demand for this feature coming from? As a language feature, I'm really struggling to come up with a convincing scenario for this that isn't purely to address the needs of three audiences:
- Trainers and MS presenters demoing LINQ
- Authors of books on LINQ
- MS evangelists demoing how little code you need to write to initialise a collection in .NET 3.5
It's a syntax feature designed to allow a demo or powerpoint slide to get the sample data set up in as few lines as possible so you can cut to the chase, which is valuable in a way, but... not a productivity enhancer for real programs. But of course, it's the kind of thing Scottgu wants to shout about because, let's be honest, he spends a lot of time hanging around with evangelists, authors, and trainers, and it makes his life easier when he's trying to present LINQ examples.
Okay - one other possibility - you might need to can some data for a testcase, and I could conceive of this syntax being of use in that situation. Any others anyone can think of? I'm struggling here...
Incidentally, if you had a non-default constructor for your Person class, you could generate that collection in only a few lines of .NET 2.0 code, anyway:
private static IEnumerable buildPeople()
{
yield return new Person("Scott", "Guthrie", 32);
yield return new Person("Bill", "Gates", 50);
yield return new Person("Susanne", "Guthrie", 32);
}
...
List people = new List(buildPeople());
That wouldn't look terribly out of place inside a test fixture.
Definitely feels like a syntax feature in search of a problem to me.