1.6. Object Initialization Expressions

The code in Listing 1-1 used another C# 3.0 feature called object initialization expressions:

List<Person> people = new List<Person> {
    new Person() { ID = 1,
                   IDRole = 1,
                   LastName = "Anderson",
                   FirstName = "Brad"},
    new Person() { ID = 2,
                   IDRole = 2,
                   LastName = "Gray",
                   FirstName = "Tom"}
            };

Just like an array initializer, an object initialization expression allows us to initialize a new object without calling its constructor and without setting its properties. Let's look at an example in Listing 1-6.

Example 1-6. Using an Object Initialization Expression
// The standard object creation and initialization
Person p1 = new Person();
p1. FirstName = "Brad";
p1.LastName = "Anderson";
ObjectDumper.Write(p1);

// The object initialization expression
Person p2 = new Person { FirstName="Tom", LastName = "Gray" };
ObjectDumper.Write(p2);

With object initialization expressions you can create an object directly and set its properties using just one statement. However, you can also write code like in Listing 1-4 without specifying the class you are instantiating.

.Select(p => new { p.FirstName, p.LastName }

It's not an error; it's another new feature called anonymous types, and I'll cover it next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.40.63