Iron Academy Logo
Learn C#

Understanding C# Arrays

Layla Porter
21m 53s

Arrays in C# are a fundamental data structure that allow developers to store a collection of elements of the same type in contiguous memory locations. Arrays can be one-dimensional, or multidimensional arrays, or jagged.

This article on C# arrays is inspired by Layla Porter's educational video, "C# for Beginners Part 5 - Arrays and More Loops." In her video, Layla dives into the fundamentals of arrays and introduces more looping techniques in C#, equipping viewers with essential skills to manage collections and iterate through data effectively.

Understanding Arrays

Layla begins by explaining arrays as fixed-length collections in C#. Unlike some other programming languages where arrays can change size dynamically, arrays in C# are immutable once created. This means their size cannot be altered after initialization due to memory allocation constraints.

Simple Console Interaction: Choosing Your Favourite Cheese

In the following code, in contrary to arrays, Layla (1:50) first demonstrates how a user can be presented with a list of items from which they can choose.

Console.WriteLine("Hello, what is your favourite cheese from this list?");
Console.WriteLine("1. Stilton");
Console.WriteLine("2. Cheddar");
Console.WriteLine("3. Pineapple");
Console.WriteLine("4. Brie");
var favouriteCheese = Console.ReadLine();
Console.WriteLine($"Here is a lump of {favouriteCheese} cheese!");
Console.WriteLine("Hello, what is your favourite cheese from this list?");
Console.WriteLine("1. Stilton");
Console.WriteLine("2. Cheddar");
Console.WriteLine("3. Pineapple");
Console.WriteLine("4. Brie");
var favouriteCheese = Console.ReadLine();
Console.WriteLine($"Here is a lump of {favouriteCheese} cheese!");

This code first uses Console.WriteLine to print a message to the console that asks the user what their favorite cheese is. It then uses Console.WriteLine four more times to print a list of cheeses to the console. The code then uses Console.ReadLine to read the user's input from the console and stores it in the variable favouriteCheese. Finally, the code uses Console.WriteLine again to print a message to the console that includes the user's favorite cheese.

Layla at 2:04, executes this code to show how it works:

Declare an Array - Array Initialization

To illustrate, Layla starts by demonstrating how to declare and initialize an array of strings, in this case, a list of cheeses that were initially presented to the user as a menu. She introduces the syntax for defining a one-dimensional array (2:30) and populating it with initial values using curly braces (2:54).

string[] cheeses = { "Brie", "Cheddar", "Stilton", "Gouda" };
string[] cheeses = { "Brie", "Cheddar", "Stilton", "Gouda" };

She emphasizes the importance of zero-based indexing in arrays, where the first element single dimensional array is accessed using index 0. Layla then proceeds to show how to iterate over arrays using a for loop. This loop structure is pivotal in programming as it allows repetitive execution of code based on a specified condition.

Implementing Loops

Moving on to loops, Layla introduces the for loop with its three essential components: initializer, condition, and iterator. This loop is used to iterate through the elements of an array based on its length.

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

She at 4:44 emphasizes that cheeses.Length gives the number of elements in the array, ensuring the loop iterates precisely through each element. The variable i works as array variable for iterating through indexes. This effectively prints out individual array elements without writing the Console.WriteLine method over and over again as shown above without accessing array elements. Layla at 6:17, runs the application to show the output of this for loop to be exactly the same as previous example:

Sorting and Mutability

Layla explains the benefit of sorting and then at 7:17, she demonstrates sorting an array alphabetically using the Sort method, cautioning that sorting actually creates a new array behind the scenes due to the immutability of arrays in C#. This is a crucial point for understanding how data manipulation affects memory and performance.

Array.Sort(cheeses);
Array.Sort(cheeses);

She also shows how individual elements within the array can be modified directly without creating a new array (8:10), illustrating mutability within immutability. The index of the element to be replaced is passed within square brackets after the cheeses array type variable:

cheeses[0] = "Roquefort";
cheeses[0] = "Roquefort";

This will swap the array element "Stilton" at index 0 with new array int. value "Roquefort".

Updating the Cheese List: Handling New Entries (8:46)

Layla explains how we can append values to an existing list. This involves taking the existing values and the new value, creating a new array that includes both, and updating our reference to point to this new array. The following code demonstrates how it works:

var favouriteCheese = Console.ReadLine();

bool containsFavourite = false;

foreach(var cheese in cheeses)
{
  if(favouriteCheese == cheese)
  {
    containsFavourite = true;
  }                                                   
}
if(!containsFavourite)
{
  cheeses cheeses.Append(favouriteCheese).ToArray();
}
var favouriteCheese = Console.ReadLine();

bool containsFavourite = false;

foreach(var cheese in cheeses)
{
  if(favouriteCheese == cheese)
  {
    containsFavourite = true;
  }                                                   
}
if(!containsFavourite)
{
  cheeses cheeses.Append(favouriteCheese).ToArray();
}

This example shows the process in a simple way using basic array operations and a foreach loop to check if the cheese is already in the list. If it's not, Layla appends it (13:33) to the array using Lists Append method.

Layla at 13:50 says the code errors because cheeses and the result of Append are different types. Append returns an IEnumerable, an interface for collections. To fix this, we convert the IEnumerable to an empty array type by using ToArray() method and then assign it back to cheeses. Layla notes that the yellow squiggly line is a compiler warning indicating potential issues, like favouriteCheese being null, but we are ignoring safety checks in this demo.

Updating and Printing the Cheese List

Layla explains that once we have added a new item to our array, we should print the updated list to the screen. To do this, we use a for loop, printing each element alongside default value and its index to show that the array now contains five items, with indices ranging from 0 to 4.

Console.WriteLine("The new list:");

for (var i = 0; i < cheeses.Length; i++)
{
  Console.WriteLine(i + " " + cheeses[i]);
}

Console.WriteLine($"Here is a lump of {favouriteCheese} cheese!");
Console.WriteLine("The new list:");

for (var i = 0; i < cheeses.Length; i++)
{
  Console.WriteLine(i + " " + cheeses[i]);
}

Console.WriteLine($"Here is a lump of {favouriteCheese} cheese!");

This demonstrates the dynamic nature of arrays in C#, showing how to add new elements and verify the update by printing the array's contents.

Layla then run's the application to display the newly added cheese (15:19): (below image can be better?)

Enhancing with Object Arrays

To broaden understanding, Layla introduces arrays of objects by creating a Cheese class with properties for Name and Strength (16:14). She then replaces the string to create an array of cheeses with an array of Cheese objects and demonstrates how to access properties within objects during iteration (17:46).

Cheese[] cheeses = new Cheese[]
{
    new Cheese("Stilton", 3),
    new Cheese("Cheddar", 2),
    new Cheese("Pineapple", 1),
    new Cheese("Brie", 2)
};

cheeses[0] = new Cheese("Roquefort", 4);
Cheese[] cheeses = new Cheese[]
{
    new Cheese("Stilton", 3),
    new Cheese("Cheddar", 2),
    new Cheese("Pineapple", 1),
    new Cheese("Brie", 2)
};

cheeses[0] = new Cheese("Roquefort", 4);

This segment provides a foundational understanding of how arrays can encapsulate complex data structures, offering flexibility and power in programming.

Utilizing Cheese Object in Loops

Layla now shows how to print all the elements of the updated list to the screen. In this scenario, each cheese is represented as an object with properties Name and Strength. The for loop iterates through this array of Cheese objects where each iteration handles a single array element directly.

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

This loop simplifies access to the properties of Cheese object stored in cheeses array. Layla at 20:34 runs the program and output is as follows: (Below image can be better?)

Conclusion

In conclusion, Layla Porter's tutorial on arrays and loops in C# provides a solid foundation for beginners to understand these essential concepts. By mastering arrays and various loop constructs, aspiring C# developers can effectively manipulate data structures and iterate through collections in their programs. Understanding these fundamentals is crucial for building more complex applications and exploring further aspects of C# programming.

By following Layla's examples and explanations, beginners can gain confidence in using arrays and loops effectively in their own C# projects. For more in-depth coverage of C# collections and advanced two-dimensional and jagged arrays, learners are encouraged to explore subsequent tutorials and practical exercises.