tags:

views:

334

answers:

8

Why do i receive error in the following declaration ?

List<int> intrs = new List<int>().AddRange(new int[]{1,2,3,45});

Error :Can not convert type void to List ?

+15  A: 

Because AddRange function does not return a value. You might need to perform this in two steps:

List<int> intrs = new List<int>();
intrs.AddRange(new int[]{1,2,3,45});
Darin Dimitrov
+5  A: 

AddRange does not return the list it has added items to (unlike StringBuilder). You need to do something like this:

List<int> intrs = new List<int>();
intrs.AddRange(new int[]{1,2,3,45});
thecoop
+2  A: 

AddRange() is declared as:

public void AddRange(object[]);

It does not return the list.

scottm
+6  A: 

Because AddRange modifies the specified list instead of returning a new list with the added items. To indicate this, it returns void.

Try this:

List<int> intrs = new List<int>();
intrs.AddRange(new int[]{1,2,3,45});

If you want to create a new list without modifying the original list, you can use LINQ:

List<int> intrs = new List<int>();
List<int> newIntrs = intrs.Union(new int[]{1,2,3,45}).ToList();
// intrs is unchanged
dtb
+5  A: 

You could also use a collection initializer (assuming C# 3.0+).

List<int> intrs = new List<int> { 1, 2, 3, 45 };

Edit by 280Z28: This works for anything with an Add method. The constructor parenthesis are optional - if you want to pass thing to a constructor such as the capacity, you can do so with List<int>(capacity) instead of just List<int> written above.

Here's an MSDN reference for details on the Object and Collection Initializers.

Dictionary<string, string> map = new Dictionary<string, string>()
    {
        { "a", "first" },
        { "b", "second" }
    };
Chris Marisic
Yes I am using C# 3.0.Thanks.
udana
But constructor is not declared ???Is it syntatic sugar?
udana
It is syntactic sugar - see http://msdn.microsoft.com/en-us/library/bb384062.aspx
thecoop
+1  A: 

By the way in C# 3.x (not sure about 2.0) you can do either of

List<int> intrs = new List<int>{1,2,3,45};
List<int> intrs = new []{1,2,3,45}.ToList(); // with Linq extensions

Besides other answers, you can add your own extension method that will add range and return list (not that it's a good practice).

queen3
A: 

BTW, if you had already declared intrs, you could have done it with parentheses:

(intrs = new List<int>()).AddRange(new int[] { 1, 2, 3, 45 });

However, I like the initialization syntax better.

Neil Whitaker
A: 

Although others have already mentioned that AddRange does not return a value, based on the samples given for alternatives it should also be remembered that the constructor of List will take an IEnumerable of T as well in addition to the code previously mentioned that is .NET 3.5+

For example:

List<int> intrs = new List<int>(new int[]{2,3,5,7});
David in Dakota