How to declare and initialize a list in C#?


To declare and initialize a list in C#, firstly declare the list −

List<string> myList = new List<string>()

Now add elements −

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

Through this, we added six elements above.

The following is the complete code to declare and initialize a list in C# −

Example

 Live Demo

using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      // Initializing collections
      List<string> myList = new List<string>() {
         "one",
         "two",
         "three",
         "four",
         "five",
         "size"
      };
      Console.WriteLine(myList.Count);
   }
}

Output

6

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements