430
votes

How is it possible to initialize (with a C# initializer) a list of strings? I have tried with the example below but it's not working.

List<string> optionList = new List<string>
{
    "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();
12
there's an example here for a multidimensional list in the answer to this question stackoverflow.com/questions/34473358/… - barlop

12 Answers

519
votes
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
635
votes

Just remove () at the end.

List<string> optionList = new List<string>
            { "AdditionalCardPersonAdressType", /* rest of elements */ };
162
votes

You haven't really asked a question, but the code should be

List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"}; 

i.e. no trailing () after the list.

38
votes
var animals = new List<string> { "bird", "dog" };
List<string> animals= new List<string> { "bird", "dog" };

Above two are the shortest ways, please see https://www.dotnetperls.com/list

16
votes

Your function is just fine but isn't working because you put the () after the last }. If you move the () to the top just next to new List<string>() the error stops.

Sample below:

List<string> optionList = new List<string>()
{
    "AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};
7
votes

This is how you initialize and also you can use List.Add() in case you want to make it more dynamic.

List<string> optionList = new List<string> {"AdditionalCardPersonAdressType"};
optionList.Add("AutomaticRaiseCreditLimit");
optionList.Add("CardDeliveryTimeWeekDay");

In this way, if you are taking values in from IO, you can add it to a dynamically allocated list.

3
votes

Move round brackets like this:

var optionList = new List<string>(){"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"};
2
votes

There is something else that you might be missing that hasn't been mentioned. I think it might be the problem you are having as I suspect you already tried removing the trailing () and still got an error.

First, like others have mentioned here, in your example you do need to remove the trailing ();

But, also, note that List<> is in the System.Collections.Generic namespace.

So, you need to do one of the following two options: [#1 below is probably the more preferred option]

(1) Include the use of the namespace at the top of your code with: using System.Collections.Generic;

or

(2) Put the fully qualified path to List in your declaration.

System.Collections.Generic.List optList=new System.Collections.Generic.List { "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay" };

Hope that helps.

The error message you receive when you implement List correctly but don't include the System.Collections.Generic namespace is misleading and not helpful:

"Compiler Error CS0308: The non-generic type List cannot be used with type arguments."

PS - It gives this unhelpful error because if you don't specify that you intend to use System.Collections.Generic.List the compiler assumes you are trying to use System.Windows.Documents.List.

1
votes

One really cool feature is that list initializer works just fine with custom classes too: you have just to implement the IEnumerable interface and have a method called Add.

So for example if you have a custom class like this:

class MyCustomCollection : System.Collections.IEnumerable
{
    List<string> _items = new List<string>();

    public void Add(string item)
    {
        _items.Add(item);
    }

    public IEnumerator GetEnumerator()
    {
        return _items.GetEnumerator();
    }
}

this will work:

var myTestCollection = new MyCustomCollection()
{
    "item1",
    "item2"
}
0
votes

I have seen the content tag C#, but if someone could use Java (the same search terms lead here):

List<String> mylist = Arrays.asList(new String[] {"element1", "element2", "element3" }.clone());
0
votes

The right way to initialize along with declaration is :

List<string> optionList = new List<string>()
{
    "AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};
-7
votes

This is how you would do it.

List <string> list1 = new List <string>();

Do Not Forget to add

using System.Collections.Generic;