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 opt
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
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.
List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");
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"
}
This is how you would do it.
List <string> list1 = new List <string>();
Do Not Forget to add
using System.Collections.Generic;
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