Friday, April 23, 2021

C# List Declaration and Initialization

using System;
using System.Collections.Generic;

namespace Console_List_Declaration_and_Initialization
{
    class Program
    {
        static void Main(string[] args)
        {
            //A List has no fixed size unlike array
            //Declare and then Initialize
            List<int> Intlist; //reference variable
            Intlist = new List<int>(); // created with int default values 0 and referrred it using the reference variable
            Console.WriteLine("Initial capacity of Intlist: "+ Intlist.Capacity);
            //Declare and Initialize with default value in a statement
            List<string> persons = new List<string>();
            persons.Add("Ajeet");
            persons.Add("Mohan");
            persons.Add("Rina");
            persons.Add("Tom");
            //initialized with array
            string[] names = { "Jon", "Bob", "Sofia", "Lucy" };
            persons.AddRange(names);
            //Declare and Initialize with custom values in a { } block
            List<string> colors = new List<string>()
            {
                "pink", "blue", "red", "green", "cyan", "white"
            };
            Console.WriteLine("\nList persons");
            foreach (var p in persons)
            {
                Console.WriteLine(p);
            }
            Console.WriteLine("\nList names");
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
            Console.WriteLine("\nList colors");
            foreach (var c in colors)
            {
                Console.WriteLine(c);
            }
            Console.Read();
        }
    }
}

OUTPUT:
Initial capacity of Intlist: 0

List persons
Ajeet
Mohan
Rina
Tom
Jon
Bob
Sofia
Lucy

List names
Jon
Bob
Sofia
Lucy

List colors
pink
blue
red
green
cyan
white

No comments:

Post a Comment

Hot Topics