Home » C#.Net

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?
Submitted by IncludeHelp, on March 11, 2019

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

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.

List declaration with initialization

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.

Examples:

    //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 create/declare a list with initialization

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>{
				"Manju", "Amit", "Abhi", "Radib", "Prem"
			};

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

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

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

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


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.