Sunday, January 20, 2008

Demystifying C# 3.0 - Part 5: Object and Collection Initializers

Source:http://blah.winsmarts.com/2006/05/21/demystifying-c-30--part-5-object-and-collection-initializers.aspx
Demystifying C# 3.0 - Part 5: Object and Collection Initializers
Posted on 6/30/2006 @ 8:46 PM in #Vanilla .NET 0 comments 2639 views
As you may already be aware, I am writing up a series of posts on C# 3.0/LINQ and DLINQ, that intend to bring these technologies down to a simple, easy to digest, understandable form. These will be served in small bite sized peices - 5 minutes of your time everyday, and little strokes will fell great oaks. (I am still talking about C# 3.0)
So in this series, we have already talked about -
a) Demystifying C# 3.0 - Part 1: Implicitly Typed Local Variables "var"b) Demystifying C# 3.0 - Part 2: Anonymous Typesc) Demystifying C# 3.0 - Part 3: Extension Methodsd) Demystifying C# 3.0 - Part 4: Lambda Expressions
Today, lets talk about "Object and Collection Initializers"
First Object Initializers
Lets say, you had a class as shown below -
public class Monkey{ private string monkeyName; private int age; public string Name { get { return monkeyName; } set { monkeyName = value; } } public int Age { get { return age; } set { age = value; } } }
The above can be easily instantiated as shown below -
var gwBush = new Monkey{ Name = "George W Bush", Age = 16} ;
The above code simply calls the "setters" of "Monkey" to give you a variable called gwBush back. Note that there is no constructor that accepts the public properties as arguments.
Next, Collection Initializers
Collection initializers, are the corollary of how you'd initialize arrays. Put simply, you can initialize a collection as shown below -
List digits = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
So what is the practical upshot of this?
Look at this one line of code -
var theWhiteHouseStaff = new List { new Monkey{ Name = "George W Bush", Age = 16}, new Monkey{ Name = "Donald Rumsfield", Age = 16}, new Monkey{ Name = "Condolezza Rice", Age = 16}, new Monkey{ Name = "Dick Cheney", Age = 16} } ;
Boy that sure looks a lot cleaner than a number of temporary variables, hanging chads and recount in florida etc. .. in other words, a much cleaner and terse syntax.

Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home