Sunday, April 6, 2008

Class and Collection Initializers

Initializers allow you to set properties of a class or populate a collection in the same line that you instantiate your class/collection.

Classes
public class Person 
{
     public string First { get; set; }
     public string Last { get; set; } 
}
Before:
Person person = new Person(); 
person.First = "Mark"; 
person.Last = "Moeykens"; 
After:
Person person = new Person(){Last="Moeykens", First="Mark"};
(Notice the properties do not have to be in any order.)

Collections
Before:
List people = new List(); 
people.Add("Moeykens"); 
people.Add("Major"); 
people.Add("Hayek"); 
After:
List<string> people = new List<string>() {"Moeykens", "Major", "Hayek"};
Collection of Classes
Before:
List people = new List(); 
people.Add(new Person() {First="Mark", Last="Moeykens"}); 
people.Add(new Person() {First="Dean", Last="Major"}); 
people.Add(new Person() {First="George", Last="Hayek"}); 
After:
List people = new List() 
{
     new Person() {First="Mark", Last="Moeykens"},
     new Person() {First="Dean", Last="Major"},
     new Person() {First="George", Last="Hayek"} 
}; 
More Info: MSDN: Object and Collection Initializers