Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

People also ask

What does it mean to initialize in C?

In computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.

Can we initialize variable in C?

Unlike PASCAL, in C variables may be initialized with a value when they are declared. Consider the following declaration, which declares an integer variable count which is initialized to 10. Lets examine what the default value a variable is assigned when its declared.


var list = new List<string> { "One", "Two", "Three" };

Essentially the syntax is:

new List<Type> { Instance1, Instance2, Instance3 };

Which is translated by the compiler as

List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");

Change the code to

List<string> nameslist = new List<string> {"one", "two", "three"};

or

List<string> nameslist = new List<string>(new[] {"one", "two", "three"});

Just lose the parenthesis:

var nameslist = new List<string> { "one", "two", "three" };

List<string> nameslist = new List<string> {"one", "two", "three"} ?

Remove the parentheses:

List<string> nameslist = new List<string> {"one", "two", "three"};

It depends which version of C# you're using, from version 3.0 onwards you can use...

List<string> nameslist = new List<string> { "one", "two", "three" };