hits counter

How About Property Assignment And Collection Adding Like Object And Collection Initializers In C#?

C# 3.0 introduced object and collection initializers. It is now easier to initialize objects or collections:

var person = new Person { FirstName = "Paulo", LastName = "Morgado" };

var persons = new List<Person> { new Person { FirstName = "Paulo", LastName = "Morgado" }, new Person { FirstName = "Luís", LastName = "Abreu" } };

var personDirectory = new Dictionary<string, Person> { { "Lisboa", new Person { FirstName = "Paulo", LastName = "Morgado" } }, { "Funchal", new Person { FirstName = "Luís", LastName = "Abreu" } } };

Wouldn't be nice to be able to do the same on already created objects and collections?

But, what would the syntax used be? Something like this?

var person = new Person();
person = { FirstName = "Paulo", LastName = "Morgado" };

var persons = new List<Person>();
persons += {
    new Person { FirstName = "Paulo", LastName = "Morgado" },
    new Person { FirstName = "Luís", LastName = "Abreu" }
};

var personDirectory = new Dictionary<string, Person>();
personDirectory += {
    { "Lisboa", new Person { FirstName = "Paulo", LastName = "Morgado" } },
    { "Funchal", new Person { FirstName = "Luís", LastName = "Abreu" } }
};

What do you think of this?

No Comments