Forum

Notifications
Clear all

Learn .Net Arrays

1 Posts
1 Users
0 Reactions
9 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

In .NET (especially using C#), arrays are used to store fixed-size collections of elements of the same data type. They’re incredibly handy when you need to group related values together.


📦 Declaring and Initializing Arrays

  • Fixed-length arrays:
int[] numbers = new int[3];  // declares an array of 3 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
  • Inline initialization:
string[] colors = { "Red", "Green", "Blue" };

🔍 Accessing and Modifying Elements

  • Arrays use zero-based indexing:
Console.WriteLine(colors[1]);  // prints "Green"
colors[2] = "Yellow";  // updates third item

🔄 Looping Through Arrays

foreach (string color in colors)
{
    Console.WriteLine(color);
}

Or using for:

for (int i = 0; i < colors.Length; i++)
{
    Console.WriteLine(colors[i]);
}

🧠 Array Properties and Methods

  • Length: Gets the total number of elements
int count = colors.Length;
  • Array.Sort(): Sorts the array
  • Array.Reverse(): Reverses the order
  • Array.IndexOf(): Finds index of a value

🧬 Multidimensional and Jagged Arrays

  • Multidimensional array (matrix-like):
int[,] grid = new int[2, 3];  // 2 rows, 3 columns
grid[0, 1] = 42;
  • Jagged array (array of arrays):
int[][] jagged = new int[2][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };

Arrays are super efficient and tightly integrated into the .NET framework. 


   
Quote
Share: