[LINQ via C# series]
Take this Person type as an example:
public class Person
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
Object initializer
In C# 2.0 we create an Person instance and initialize it like this:
Person person = new Person();
person.Name = "Mark";
person.Age = 18;
While in C# 3.0, we can use the object initializer syntactical shortcut:
Person person = new Person()
{
Name = "Mark",
Age = 18
};
This code will be compiled into:
Person <>g__initLocal0 = new Person();
<>g__initLocal0.Name = "Mark";
<>g__initLocal0.Age = 18;
Person person = <>g__initLocal0;
Collection initializer
In C# 2.0 we initialize an collection like this:
Collection<Person> persons = new Collection<Person>();
persons.Add(mark);
persons.Add(steven);
Now in C# 3.0 we can write code like this:
Collection<Person> persons = new Collection<Person>()
{
mark,
steven
};
The compiler will look up the Add() method automatically:
Collection<Person> <>g__initLocal0 = new Collection<Person>();
<>g__initLocal0.Add(mark);
<>g__initLocal0.Add(steven);
Collection<Person> persons = <>g__initLocal0;
To use the collection initializer on a collection, these are needed to do:
- Implement System.IEnumerable for the collection type
- Define a Add() instance method for the collection type. The method takes at least one parameter, and its return value is ignored
Here is a shortest sample. Collection initializer can be applied to the following collection:
public class PersonCollection : IEnumerable
{
public void Add(Person person)
{
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
If the Add() method takes more than one parameters, this syntax should be used:
Dictionary<string, int> persons = new Dictionary<string, int>()
{
{ "Mark", 18 }, // Compiled to Add("Mark", 18).
{ "Steven", 18 } // Compiled to Add("Steven", 18).
};