List declaration with initialization in C#

C# | List declaration with initialization: Here, we are going to learn how to create/declare a list with the initialization? By IncludeHelp Last updated : April 15, 2023

The task is to create/declare a list with an initializer list in C#.

What is C# List?

A list is used to represent the list of the objects, it is represented as List<T>, where T is the type of the list objects/elements.

A list is a class which comes under System.Collections.Generic package, so we have to include it first.

How to Declare and Initialize a List?

To declare and initialize a list with the elements/objects, we use the following syntax,

List<T> list_name= new List<T> {list_of_objects/elements};

Here, T is the type and list_name is the name of the list.


//an integer list
List<int> int_list = new List<int> { 10, 20, 30, 40, 50 };

//a string list 
List<string> str_list = new List<string>{
    "Manju", "Amit", "Abhi", "Radib", "Prem"

Here, int_list is a list of integer elements and str_list is a list of string elements.

C# Program to Declare and Initialize a List

using System;
using System.Text;
using System.Collections.Generic;

namespace Test {
  class Program {
    static void Main(string[] args) {
      //an integer list
      List < int > int_list = new List < int > {10, 20, 30, 40, 50};

      //a string list 
      List < string > str_list = new List < string > {

      //printing list elements
      Console.WriteLine("int_list elements...");
      foreach(int item in int_list) {
        Console.Write(item + " ");

      Console.WriteLine("str_list elements...");
      foreach(string item in str_list) {
        Console.Write(item + " ");

      //hit ENTER to exit


int_list elements...
10 20 30 40 50
str_list elements...
Manju Amit Abhi Radib Prem

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.