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 { getreturn monkeyName; } set { monkeyName = value; } }
public int Age { getreturn 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<int> digits = new List<int> { 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<Monkey>
{
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}
} ;

Comments are closed.

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: