How to declare and initialize a list in C#?

CsharpProgrammingServer Side Programming

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
raja
Published on 06-Aug-2018 10:58:04
Advertisements