Five Minute C# — Lesson 8

Storing variables inside lists and arrays

Alexander Laurence
Five Minute C#
7 min readOct 29, 2018

--

Lessons: 12345678910 ・ 11 ・ 12 ・ 13 ・ 14

So what’s the problem?

Remember the big messy code we had in our previous lesson. We can tidy that up! In fact, there is no need to keep on passing parameters in this way.

I mean, it’s not wrong, it certainly works! But you probably want to do things a better way. Although before we get into how we can solve this problem, let's get back to basics.

In C#, we can make use of objects such as arrays and lists to store numerous variables. Think of them as containers. However, they are not the same thing!

Let’s begin by declaring an array on an integer type called numbers. We do this by adding the square brackets suffix [] to the type:

int[] numbers;

Arrays can hold any number of integers or strings! But first let’s instantiate it for it to work in the way we want. You can do this with an operator called new to create a new object:

int[] numbers = new int[];

However it is an empty array, and there’s no point having an empty array. Let’s assign some values to the newly initialised array.

int[] numbers = new int[3];

This is saying we have a new array called numbers which will take 3integer values. You can therefore say that this array has a size of 3.

Cool, now let’s give those 5 elements a value. You can do this by individually specifying the index number. In programming, you begin counting at 0. So the first value in an index would be 0 followed by 1,2,3, etc.

So if we want to give our first element a value of -2, our second element a value of 6, and our third/final element a value of 1, we can say:

numbers[0] = -2;
numbers[1] = 6;
numbers[2] = 1;

I hope this makes sense! The first index is always 0 (not 1).

You can also assign these values at the time of declaration too. By doing so, there will be no need to instantiate the array. Just specify the index values inside curly braces like so:

int[] numbers = {-2, 6, 1};

By virtue of not instantiating it, the array has not been initialised into the memory. Therefore, it cannot help us with more complicated tasks. If you want to create and initialise the array, you will have to use new:

int[] numbers = new int[3] numbers {-2, 6, 1};

In fact, you can also omit the size of the array (if you want to assign the values at the point of declaration) and it will still work.

int[] numbers = new int[] numbers {-2, 6, 1};

By assigning a size, we are telling the array we want it to only take in a fixed number of values. This has its advantages and disadvantages. For example, if you don’t want an array that can take any number of values, you will want to assign fixed size for it.

You can have multiple arrays which interact with each other. Have fun with it! Here we have the score array equal to the numbers array:

int[] numbers = new int[] {-2, 6, 1};
int[] score = numbers;

So, now that we know all this… What can we do to fix our messy code from the previous lesson? Let’s remind ourselves about that code:

using System;
namespace Program
{
class example
{
public int biggest(int arg1, int arg2, int arg3, int arg4)
{
Console.WriteLine(arg1, arg2, arg3, arg4);
return Math.Max(arg1, arg2, arg3, arg4);
}
public int smallest(int arg1, int arg2, int arg3, int arg4)
{
Console.WriteLine(arg1, arg2, arg3, arg4);
return Math.Min(arg1, arg2, arg3, arg4);
}
public int distFrom_zero(int arg)
{
Console.WriteLine(arg);
return Math.Abs(arg);
}
}
}

Instead of writing down int arg1, int arg2, etc… we can use arrays!

Let’s create an array in the same way as before. We want to call it args, give it an integer type:

int[] args;

We can put this right into our function as a parameter!

public int biggest(int[] args)
{
}

Now we need to work out how to use the max math method. For this we’ll need to import the System.Linq module. Then, set args.Max() and store that into its own integer variable called maxArg.

using System;
using System.Linq;
namespace Program
{
public class example
{
public int biggest(int[] args)
{
int maxArg = args.Max();
}
}
}

Now we can tell the function to return the value of maxArg.

using System;
using System.Linq;
namespace Program
{
public class example
{
public int biggest(int[] args)
{
int maxArg = args.Max();
return maxArg;
}
}
}

That’s done! Now we can do the same thing for the smallest() function.

using System;
using System.Linq;
namespace Program
{
public class example
{
public int biggest(int[] args)
{
int maxArg = args.Max();
return maxArg;
}
public int smallest(int[] args)
{
int minArg = args.Min();
return minArg;
}
public int distFrom_zero(int arg)
{
Console.WriteLine(arg);
return Math.Abs(arg);
}
}
}

Look how nice it looks! Let’s test it out…

Let’s call our biggest() function and input the following set of numbers:

Console.WriteLine(biggest(new int[] {1,2,3,4,5}));

It will give us:

5

Since 5 is the biggest number, the Math.Max has correctly calculated the result from the array.

How about the smallest() function?

Console.WriteLine(smallest(new int[] {1,2,3,4,5}));

This will give us:

1

Since 1 is the smallest number. Again, Math.Min has correctly calculated the result from the array.

You did it! That’s one clean and functional code you got there.

Before we finish, let’s briefly talk about lists and how they compare to arrays.

In order to create a list, we need to firstly call List, specify its type using angled brackets <>, give it a name, and initialise it. For example, let’s use the strings type this time:

List<string> Food = new List<string>();

Great! Now we have a list called Food which holds strings. But how do we populate the list?

As you can notice, there are no square brackets for lists. Lists are not fixed in size, and therefore are dynamically sized (while arrays are fixed in size). And so, we can simple add to the list by appending the .Add() suffix like so:

List<string> Food = new List<string>();
Food.Add("Apples");
Food.Add("Pizza");
Food.Add("Avocado");

Pretty simple, right? Let’s do something crazy. We can even add an entire array into a list! Let’s make a string array this time.

string[] shoppingList = new string[3];

Instead of .Add(), we’ll use .AddRange() like so to add the array:

List<string> Food = new List<string>();
Food.AddRange(shoppingList);

Although at the moment, we have not passed any arguments into args, so it is an empty array. But you can always assign values to your array at anytime and it will update the list automatically. For example:

shoppingList[0] = "Bananas";
shoppingList[1] = "Cakes";
shoppingList[2] = "Carrots";

And as previously discussed, you can also plug it all in one go.

List<string> Food = new List<string>();
string[] shoppingList = new string[]
{
"Bananas",
"Cakes",
"Carrots"
};
Food.AddRange(shoppingList);

Side note: .AddRange() doesn’t only work with arrays, you can concatenate lists too. You do this by passing the list name (instead of the array name) as the parameter.

Brilliant! Now “Bananas”, “Cakes”, and “Carrots” from my shoppingList array is added to my Food list. I hope that wasn’t too confusing!

We can add to lists, but what if I want to remove a value from the list? Then use the .Remove() to remove a specific value or .RemoveAt() to remove a value at a specific index.

I want to remove Bananas. I can do this using either .Remove() or .RemoveAt() like so:

Food.Remove("Banana");

Or

Food.RemoveAt(0);

Since the value “Banana” is first on the list.

In general, I find that it’s good practice to make use of lists rather than arrays in C#. This is because lists are easily sorted, searched through, and manipulated in C# than arrays are because of all of the built-in list functionalities in the language. It is for this reason that lists are used more often than arrays. But having said that, there are good reasons for using arrays. For example, if your data is unlikely to grow or if you have a large dataset which requires indexing each value.

Woah. I hope you didn’t forget our unsolved problem we had back there! Let’s get crackin’ in our next lesson. Good job!

--

--

Alexander Laurence
Five Minute C#

Alex graduated from the University of Edinburgh with a Masters degree in Neuroscience. He spent 3 years teaching and now runs his own tech venture.