C#: Is Implicit Arraylist assignment possible

arraylistc++

I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.

For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:

int[] IntArray = {1,2,3};

Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.

Best Solution

Depending on the version of C# you are using, you have different options.

C# 3.0 has collection initializers, detail at Scott Gu's Blog

Here is an example of your problem.

ArrayList list = new ArrayList {1,2,3};

And if you are initializing a collection object, most have constructors that take similar components to AddRange, although again as you mentioned this may not be an option.