Array & ArrayList class

Array & ArrayList class

In C#, an array is a fixed-size collection of elements of the same data type, whereas an ArrayList is a dynamic collection that can grow or shrink in size as needed.

To create an array in C#, you can use the following syntax:

csharp

Copy code

dataType[] arrayName = new dataType[arraySize];

For example, to create an array of integers with a size of 5, you can write:

csharp

Copy code

int[] myArray = newint[5];

To access an element of an array, you can use the following syntax:

csharp

Copy code

arrayName[index];

For example, to access the third element of the “myArray” array, you can write:

csharp

Copy code

int thirdElement = myArray[2];

To create an ArrayList in C#, you can use the following syntax:

csharp

Copy code

ArrayList arrayListName = new ArrayList();

To add an element to an ArrayList, you can use the Add method:

csharp

Copy code

arrayListName.Add(element);

For example, to add an integer to an ArrayList, you can write:

csharp

Copy code

arrayListName.Add(42);

To access an element of an ArrayList, you can use the following syntax:

csharp

Copy code

arrayListName[index];

For example, to access the third element of an ArrayList, you can write:

csharp

Copy code

int thirdElement = (int)arrayListName[2];

Note that since ArrayList can store elements of different data types, you need to cast the retrieved element to the correct data type. In the above example, we cast the retrieved element to an integer using the (int) syntax.

Arrays and String
Jagged Arrays

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?