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?

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

  • Ruslan Urban says:

    I think, you can implement this using extension methods for generic List and Dictionary classes.
    e.g.

    public static class Extensions {

    public static List operator +(this List list, List anotherList)
    {…}

    public static List operator +(this List list, TType item)
    {…}

    public static Dictionary operator +(this IDictionary dictionary, IDictionary anotherDictionary)
    {…}

    public static Dictionary operator +(this Dictionary list, DictionaryEntry)
    {…}

    }

  • Ruslan Urban says:

    I think, it can be done using extension methods. E.g.

    public static class Extensions {

    public static List operator +(this List list, List anotherList)
    {…}

    public static List operator +(this List list, TType item)
    {…}

    public static Dictionary operator +(this IDictionary dictionary, IDictionary anotherDictionary)
    {…}

    public static Dictionary operator +(this Dictionary list, DictionaryEntry)
    {…}

    }

  • paulo says:

    At this point, you cannot add extension operators.

  • Brian Johnston says:

    I think it would be great. I constantly find myself cussing because you can’t do it.

  • paulo says:

    One can always dream.