How to initialize a list of strings (List<string>) with many string values

C#StringList

C# Problem Overview


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"
}();

C# Solutions


Solution 1 - C#

Just remove () at the end.

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

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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"
};

Solution 6 - C#

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.

Solution 7 - C#

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"
}

Solution 8 - C#

Move round brackets like this:

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

Solution 9 - C#

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.

Solution 10 - C#

The right way to initialize along with declaration is :

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

Solution 11 - C#

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());

Solution 12 - C#

If you are using C# 9.0 and up you can use the new feature target-typed new expressions Link

Example:

List<string> stringList = new(){"item1","item2", "item3"} ;

Solution 13 - C#

This is how you would do it.

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

Do Not Forget to add

using System.Collections.Generic;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBilgin Kılı&#231;View Question on Stackoverflow
Solution 1 - C#PadelView Answer on Stackoverflow
Solution 2 - C#ZenzerView Answer on Stackoverflow
Solution 3 - C#UnslicedView Answer on Stackoverflow
Solution 4 - C#SujoyView Answer on Stackoverflow
Solution 5 - C#Marcello MelloView Answer on Stackoverflow
Solution 6 - C#Enye Aaron ShiView Answer on Stackoverflow
Solution 7 - C#adospaceView Answer on Stackoverflow
Solution 8 - C#Andrew KozlovView Answer on Stackoverflow
Solution 9 - C#Todd AlbersView Answer on Stackoverflow
Solution 10 - C#Pawan AgnihothriView Answer on Stackoverflow
Solution 11 - C#Martin ZeitlerView Answer on Stackoverflow
Solution 12 - C#Cyber ProgsView Answer on Stackoverflow
Solution 13 - C#Muhammad AliView Answer on Stackoverflow