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
Comments (0)