Arrays in C# Language
Arrays are fundamental data structures in C# that allow you to store and manage collections of items of the
same data type. They provide a convenient way to work with multiple values of the same type, making it easier to organize and manipulate data in your C# programs. In this post, we’ll explore the basics of arrays in C# and provide examples to illustrate their usage.Declaring Arrays
In C#, arrays are declared by specifying the data type of the elements they will contain, followed by the name of the array and square brackets []
. Here’s a simple declaration of an integer array:
int[] myIntArray;
You can also initialize the array at the same time:
int[] myIntArray = new int[5]; // Creates an array of 5 integers.
Initializing Arrays
C# provides several ways to initialize arrays. You can use the new
keyword to create a new instance of an array with a specified size:
int[] myIntArray = new int[5];
Alternatively, you can use an array initializer to assign values directly:
int[] myIntArray = { 1, 2, 3, 4, 5 };
Accessing Elements
You can access individual elements of an array by using square brackets and an index. C# arrays are zero-based, so the first element has an index of 0, the second element has an index of 1, and so on. For example:
int[] myIntArray = { 1, 2, 3, 4, 5 };
int thirdElement = myIntArray[2]; // Accessing the third element (which is 3).
Modifying Arrays
Arrays in C# are mutable, meaning you can change the values of their elements after initialization. Here’s an example of modifying an element:
int[] myIntArray = { 1, 2, 3, 4, 5 };
myIntArray[1] = 6; // Modifying the second element to be 6.
Iterating through Arrays
A common operation with arrays is iterating through their elements. You can use for
loops to achieve this. Here’s an example of looping through an integer array and printing each element:
int[] myIntArray = { 1, 2, 3, 4, 5 };
for (int i = 0; i < myIntArray.Length; i++)
{
Console.WriteLine(myIntArray[i]);
}
Multidimensional Arrays
C# also supports multidimensional arrays. You can create 2D arrays, 3D arrays, and so on. Here’s an example of a 2D array:
int[,] my2DArray = { { 1, 2, 3 }, { 4, 5, 6 } };
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.