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
Updated on: 2020-06-20T10:28:04+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements