| by Arround The Web | No comments

Dynamic Arrays in C#

Dynamic arrays in C# are an essential data structure that allows you to create and work with arrays that can change in size during runtime. Unlike static arrays, which have a fixed size that cannot be modified once created, dynamic arrays can grow or shrink in size as needed. This makes them a versatile tool for managing collections of data that may change in size over time, further read this guide to get more information on dynamic arrays in C#.

Dynamic Arrays in C#

To create a dynamic array in C#, here is an example that demonstrates the use of dynamic arrays:

using System;
using System;
using System.Collections;

namespace Dynamic_Array
{
class Program
{
static void Main(string[] args)
{
List<int> da = new List<int>();
da.Add(23);
da.Add(21);
da.Add(24);
da.Add(27);
Console.WriteLine("Count: {0}", da.Count);
Console.Write("List: ");
da.Sort();
foreach (int i in da)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}

This is a C# code creates a dynamic array using the List class. The program initializes an empty List of integers named “da” using the constructor of the List class. Then, it adds four integer values to the list using the Add() method: 23, 21, 24, and 27.

After adding these elements, the program prints the count of the elements in the list using the Count property of the List class. The count is the number of elements in the List, which in this case is 4 and the program then sorts the list in ascending order using the List class Sort() method. It then prints the elements in the list using a foreach loop, separating each element with a space.

Conclusion

Dynamic arrays are a powerful data structure in C# that can be used to store and manipulate collections of values during runtime. With the List<T> class, it is easy to create, add to, remove from, and sort dynamic arrays in C#, this article explains what dynamic arrays are and how they can be used with the help of an example code that creates a dynamic array and then sorts its elements in descending order.

Share Button

Source: linuxhint.com

Leave a Reply