Techiehook Techiehook
Updated date May 06, 2024
We will learn how to implement dynamic arrays in C# using the List class for easy data storage and manipulation.
  • 1.1k
  • 0
  • 0

Working with Arrays in C#

In C#, you can use the List<T> class from the System.Collections.Generic namespace to create dynamic arrays.

The sample program shows how to use List<T>:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Create a List to hold integers
        List<int> dynamicArray = new List<int>();

        // Add elements to the dynamic array
        dynamicArray.Add(10);
        dynamicArray.Add(20);
        dynamicArray.Add(30);

        // Print the elements of the dynamic array
        Console.WriteLine("Elements of the dynamic array:");
        foreach (var item in dynamicArray)
        {
            Console.WriteLine(item);
        }

        // Access elements by index
        Console.WriteLine("\nAccessing elements by index:");
        Console.WriteLine("Element at index 0: " + dynamicArray[0]);
        Console.WriteLine("Element at index 1: " + dynamicArray[1]);
        Console.WriteLine("Element at index 2: " + dynamicArray[2]);

        // Remove an element
        dynamicArray.Remove(20);
        Console.WriteLine("\nAfter removing 20:");
        foreach (var item in dynamicArray)
        {
            Console.WriteLine(item);
        }

        // Check if an element exists
        Console.WriteLine("\nChecking if 20 exists:");
        Console.WriteLine(dynamicArray.Contains(20) ? "20 exists" : "20 does not exist");
    }
}

In this program, we are creating a dynamic array using List<T>, adding elements to it, accessing elements by index, removing elements, and checking if an element exists in the array.

Output:

Elements of the dynamic array:
10
20
30

Accessing elements by index:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30

After removing 20:
10
30

Checking if 20 exists:
20 does not exist

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!