Simplified collection initialization

When initializing WF4, we can do something like this:

Sequence s = new Sequence()
{
    Activities = {
        new If() ...,
        new WriteLine() ...,
    }
}

Note what Sequence.Activitiesis Collection<Activity>, but it can be initialized without a new collection ().

How can I emulate this behavior in my properties Collection<T>?

+3
source share
1 answer

Any collection that has a method Add()and implements IEnumerablecan be initialized this way. See Initializers of objects and collections for C # for more details . (The absence of a new call Collection<T>is due to the object initializer, and the ability to add inline elements is associated with the collection initializer.)

Add() .


, :

using System;
using System.Collections.ObjectModel;

class Test
{
    public Test()
    {
        this.Collection = new Collection<int>();
    }

    public Collection<int> Collection { get; private set; }

    public static void Main()
    {

        // Note the use of collection intializers here...
        Test test = new Test
            {
                Collection = { 3, 4, 5 }
            };


        foreach (var i in test.Collection)
        {
            Console.WriteLine(i);
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }  
}
+2

All Articles