DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Understanding Arrays

Meta Description: Learn all about arrays in C# with hands-on examples. Understand how to create, populate, and iterate through single and multidimensional arrays. Explore easy, medium, and advanced assignments to deepen your knowledge of array operations and apply them effectively in your C# projects

Arrays are a fundamental data structure in C#. They allow you to store multiple values of the same type in a single collection. This makes them ideal for scenarios where you need to manage multiple items, such as employee IDs, a list of products, or even song playlists.

In C#, arrays are zero-based, meaning the first element has an index of 0. Arrays have a fixed size, which is defined at the time of their creation. This fixed nature makes them very efficient when dealing with a known number of items, but they lack the flexibility to grow dynamically like collections. Arrays are also reference types, meaning they are stored on the heap, and the array variable holds a reference to this memory location.

What Are Arrays?

An array is a collection of items of the same type. You can think of it as a container that holds a specific number of values, all of the same type, accessible by an index. Let’s start with a few clear examples, including how to fill arrays.

Example 1: Creating and Filling an Array of Primitive Types

In this example, we will create an array of integers and then add values to it:

// Step 1: Declare and create an array of 4 integers
int[] employeeIds = new int[4]; 

// Step 2: Fill the array with values
employeeIds[0] = 101; // Assign value to the first position
employeeIds[1] = 102; // Assign value to the second position
employeeIds[2] = 103; // Assign value to the third position
employeeIds[3] = 104; // Assign value to the fourth position

// Step 3: Display the values in the array
for (int i = 0; i < employeeIds.Length; i++)
{
    Console.WriteLine($"Employee ID at index {i}: {employeeIds[i]}");
}
Enter fullscreen mode Exit fullscreen mode
  • Explanation:

    1. We first declare an array called employeeIds that can hold 4 integer values.
    2. We then add values to each position in the array using their respective indices.
    3. Finally, we display the values using a for loop to iterate over each element.
  • Output:

  Employee ID at index 0: 101
  Employee ID at index 1: 102
  Employee ID at index 2: 103
  Employee ID at index 3: 104
Enter fullscreen mode Exit fullscreen mode

Example 2: Creating and Filling an Array of Custom Types

Arrays can also store custom types, such as employee objects. Suppose we have an Employee class defined like this:

public class Employee
{
    public string Name { get; set; }
    public int Id { get; set; }

    public void DisplayEmployeeDetails()
    {
        Console.WriteLine($"Employee ID: {Id}, Name: {Name}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, let's create an array of Employee objects and fill it:

// Step 1: Declare and create an array for 3 Employee objects
Employee[] employees = new Employee[3];

// Step 2: Create Employee objects and assign them to the array
employees[0] = new Employee() { Name = "Bethany", Id = 1 };
employees[1] = new Employee() { Name = "George", Id = 2 };
employees[2] = new Employee() { Name = "Alice", Id = 3 };

// Step 3: Display details of each employee using a foreach loop
foreach (Employee e in employees)
{
    e.DisplayEmployeeDetails();
}
Enter fullscreen mode Exit fullscreen mode
  • Explanation:

    1. We create an array called employees to hold three Employee objects.
    2. We then instantiate each employee and assign it to a position in the array.
    3. Finally, we use a foreach loop to iterate over the array and call DisplayEmployeeDetails on each employee.
  • Output:

  Employee ID: 1, Name: Bethany
  Employee ID: 2, Name: George
  Employee ID: 3, Name: Alice
Enter fullscreen mode Exit fullscreen mode

Example 3: Using Built-in Array Functionalities

Arrays come with several built-in functionalities that can make working with them easier, such as sorting, copying, and reversing.

  • Sorting an Array: You can use the Array.Sort() method to sort an array of integers.
int[] employeeIds = { 99, 1, 55, 84, 15 };

// Step 1: Sort the array
Array.Sort(employeeIds);

// Step 2: Display the sorted values
Console.WriteLine("Sorted Employee IDs:");
foreach (int id in employeeIds)
{
    Console.WriteLine(id);
}
Enter fullscreen mode Exit fullscreen mode
  • Explanation: The Array.Sort() method sorts the elements in ascending order.

  • Output:

  Sorted Employee IDs:
  1
  15
  55
  84
  99
Enter fullscreen mode Exit fullscreen mode
  • Copying an Array: You can create a copy of an array using the CopyTo() method.
int[] employeeIdsCopy = new int[employeeIds.Length];
employeeIds.CopyTo(employeeIdsCopy, 0); // Copies all elements from employeeIds to employeeIdsCopy

Console.WriteLine("Copied Employee IDs:");
foreach (int id in employeeIdsCopy)
{
    Console.WriteLine(id);
}
Enter fullscreen mode Exit fullscreen mode
  • Explanation: The CopyTo() method copies elements from the employeeIds array to the new employeeIdsCopy array starting from index 0.

  • Output:

  Copied Employee IDs:
  1
  15
  55
  84
  99
Enter fullscreen mode Exit fullscreen mode
  • Reversing an Array: You can reverse the order of elements using the Array.Reverse() method.
Array.Reverse(employeeIds); // Reverses the order of elements

Console.WriteLine("Reversed Employee IDs:");
foreach (int id in employeeIds)
{
    Console.WriteLine(id);
}
Enter fullscreen mode Exit fullscreen mode
  • Explanation: This reverses the employeeIds array, so the elements are displayed in reverse order.

  • Output:

  Reversed Employee IDs:
  99
  84
  55
  15
  1
Enter fullscreen mode Exit fullscreen mode

Assignments: Easy, Medium, and Difficult

Now that we have a solid understanding of how to create and work with arrays, let's explore some practical assignments at different levels of difficulty to solidify these concepts.

Assignment 1: Easy - Creating and Using an Array

Task: Create an array to store and display five fruit names.

Code:

// Step 1: Declare and create an array of fruits
string[] fruits = new string[5] { "Apple", "Banana", "Orange", "Grapes", "Mango" };

// Step 2: Display each fruit using a loop
for (int i = 0; i < fruits.Length; i++)
{
    Console.WriteLine($"Fruit {i + 1}: {fruits[i]}");
}
Enter fullscreen mode Exit fullscreen mode
  • Description:

    1. Create an array named fruits with five predefined fruit names.
    2. Use a for loop to display each fruit.
  • Expected Output:

  Fruit 1: Apple
  Fruit 2: Banana
  Fruit 3: Orange
  Fruit 4: Grapes
  Fruit 5: Mango
Enter fullscreen mode Exit fullscreen mode

Assignment 2: Medium - Dynamic Array Length

Task: Create an array of employee IDs with a length specified by the user.

Code:

Console.WriteLine("How many employee IDs would you like to register?");
int length = int.Parse(Console.ReadLine());

// Step 1: Declare and create an array with the specified length
int[] employeeIds = new int[length];

// Step 2: Fill the array with user input
for (int i = 0; i < length; i++)
{
    Console.Write($"Enter employee ID {i + 1}: ");
    employeeIds[i] = int.Parse(Console.ReadLine());
}

// Step 3: Display the registered employee IDs
Console.WriteLine("\nThe registered employee IDs are:");
for (int i = 0; i < length; i++)
{
    Console.WriteLine($"Employee ID {i + 1}: {employeeIds[i]}");
}
Enter fullscreen mode Exit fullscreen mode
  • Description:

    1. Ask the user for the number of employee IDs to register.
    2. Create an array of that length and fill it with the user-provided IDs.
    3. Display all the entered IDs.
  • Expected Output (example):

  How many employee IDs would you like to register?
  3
  Enter employee ID 1: 101
  Enter employee ID 2: 102
  Enter employee ID 3: 103
  The registered employee IDs are:
  Employee ID 1: 101
  Employee ID 2: 102
  Employee ID 3: 103
Enter fullscreen mode Exit fullscreen mode

Assignment 3: Difficult - Wage Calculation Using Arrays

Task: Calculate and display wages for employees. Allow the user to input employee names and hours worked, then compute wages.

**

Code**:

Console.WriteLine("How many employees do you have?");
int employeeCount = int.Parse(Console.ReadLine());

// Step 1: Declare and create an array of Employee objects
Employee[] employees = new Employee[employeeCount];
double hourlyRate = 15.0;

// Step 2: Populate the employee array with names and hours worked
for (int i = 0; i < employeeCount; i++)
{
    Console.Write($"Enter name of employee {i + 1}: ");
    string name = Console.ReadLine();

    Console.Write($"Enter hours worked by {name}: ");
    double hoursWorked = double.Parse(Console.ReadLine());

    employees[i] = new Employee() { Name = name, Id = i + 1 };
    employees[i].PerformWork(hoursWorked);
}

// Step 3: Display the wage report for each employee
Console.WriteLine("\nEmployee Wage Report:");
foreach (Employee e in employees)
{
    e.DisplayEmployeeDetails();
    e.ReceiveWage(hourlyRate);
}
Enter fullscreen mode Exit fullscreen mode
  • Description:

    1. Ask the user for the number of employees.
    2. Create an array of Employee objects and populate it with names and hours worked.
    3. Calculate and display the wages for each employee.
  • Expected Output (example):

  How many employees do you have?
  2
  Enter name of employee 1: Alice
  Enter hours worked by Alice: 40
  Enter name of employee 2: Bob
  Enter hours worked by Bob: 35

  Employee Wage Report:
  Employee ID: 1, Name: Alice
  Worked for: 40 hours, Wage: $600.00
  Employee ID: 2, Name: Bob
  Worked for: 35 hours, Wage: $525.00
Enter fullscreen mode Exit fullscreen mode

Conclusion

Arrays in C# are a powerful tool for storing and working with collections of data. They provide several built-in functionalities for sorting, copying, and reversing the data. By starting with these easy, medium, and difficult examples, you should now feel more comfortable creating, populating, and using arrays in practical scenarios. Practice these assignments, and soon you'll be able to use arrays effectively in your projects. For scenarios requiring more flexibility, consider using collections, which allow dynamic resizing.

Top comments (0)