Arrays C Sharp
Arrays C Sharp
Arrays are fundamental data structures in C# that allow you to store multiple values of the same
type under a single variable name. They provide efficient ways to work with collections of related
data. An array is a group of like-typed variables that are referred to by a common name. And each
data item is called an element of the array. The data types of the elements may be any valid data
type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the
array specifies the number of elements present in the array.
Arrays can be initialized after the declaration. It is not necessary to declare and initialize at the
same time using the new keyword. However, Initializing an Array after the declaration, it must be
initialized with the new keyword. It can’t be initialized by only assigning values.
string[] weekDays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
Basic Arrays in C#
A C# array is a fixed-size collection that stores elements of the same data type in contiguous
memory locations. This array contains only one row for storing the values. All values of this
array are stored alongside starting from 0 to the array size. For example, a single-dimensional
array of 5 integers :
int[] numbers;
int[] scores = new int[5]; // Creates an array of 5 integers (default value of every
element will be 0)
string[] names = new string[3]; // Creates an array of 3 strings (default value for
every element will be null)
2D Arrays
Two-dimensional arrays, often called matrices, organize data in rows and columns. They're
particularly useful for grid-based applications like spreadsheets or games.
// Declaration of a 2D array
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
// Accessing elements
int value = grid[1, 2]; // Gets the value at row 1, column 2 (value 7)
Multidimensional Arrays
C# supports arrays with more than two dimensions. These can represent complex structures like
3D spaces or multi-factor data sets. It can be a 2D-array or 3D-array or more. To storing and
accessing the values of the array, one required the nested loop. The multi-dimensional array
declaration, initialization and accessing is as follows :
// 3D array declaration
{ { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };
// Accessing elements
int value = threeDArray[1, 0, 1]; // Gets the value at position [1,0,1] (value 6)
Jagged Arrays
Jagged arrays are arrays of arrays, where each sub-array can have a different length. The jagged
array elements may be of different dimensions and sizes. They're useful when data isn't uniformly
structured.
// Declaration
// Accessing elements
When working with arrays in Windows Forms applications, you can iterate through them in
various ways:
// Process array[i]
}
// For each loop (simpler syntax for single-dimension arrays)
// Process item