CHASH Tutorial



C# ARRAYS


Arrays in C#

An array in C# is a collection of variables of the same type stored in contiguous memory locations. Arrays are useful for storing multiple values in a single variable.

1. Declaring and Initializing Arrays

  • int[] numbers = new int[5]; — Declares an integer array with 5 elements (default values are 0).
  • int[] numbers = {1, 2, 3, 4, 5}; — Declares and initializes an array with values.
  • string[] fruits = new string[] {"Apple", "Banana", "Mango"}; — String array initialization.

2. Accessing and Modifying Array Elements

You access array elements by their index (starting from 0):

int[] numbers = {10, 20, 30, 40, 50};
Console.WriteLine(numbers[0]); // Output: 10

numbers[2] = 100; // Changing the third element
Console.WriteLine(numbers[2]); // Output: 100

  

3. Looping Through Arrays

Commonly, we use a for loop or foreach loop to iterate over all elements:

string[] fruits = { "Apple", "Banana", "Mango" };

// Using for loop
for (int i = 0; i < fruits.Length; i++)
{
    Console.WriteLine(fruits[i]);
}

// Using foreach loop
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

  

4. Important Points

  • Array indices always start at 0.
  • Length property gives the size of the array.
  • Arrays have a fixed size once declared — you cannot change the size later.

Summary

  • Arrays store multiple values of the same type in order.
  • Use indexes starting at 0 to access or modify elements.
  • Loop through arrays using for or foreach.
  • Arrays have a fixed size after declaration.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review