C# Arrays

Arrays are a very handy aspect in programming as they allow you to store multiple values in a single variable instead of declaring a variable for each item. For example, if you want to have a bunch of names such as “Tom”, “Tim”, “Jerry”, “Jim”, “Steve”. Instead of having each of them as separate items (variables), an array can be used.

A simple array is defined by type[] variableName;. We can then specify what we want in the array up front by doing type[] variableName = {"item1", "item2", item3" }; Note that an object or number (int) will not need to have quotes around the variables added to the array. An array of these string types can be defined as: string[] names = {"Tom", "Tim", "Jerry", "Jim", "Steve"}; This will give us a string array of each of the name we provided.

If we want to know how long an array is, we can simply get this information by doing variableName.Length;. This will tell us how many items are in the array.

We can get the data from the this array by simply using a For or Foreach loop. An example of this would be as follows:

string[] names = {"Tom", "Tim", "Jerry", "Jim", "Steve"};
for (int i = 0; i < names.Length; i++)
{
   Console.WriteLine(names[i]);
}

Or with a foreach loop:

string[] names = {"Tom", "Tim", "Jerry", "Jim", "Steve"};
foreach (string name in names)
{
   Console.WriteLine(name);
}

Replace element in array

Lets say we have item in the array we want to replace. We would have to find that index in the array and change the variable. This is simple with a for loop.

string[] names = { "Tom", "Tim", "Jerry", "Jim", "Steve" };
       for (int i = 0; i < names.Length; i++)
{
   if(names[i] == "Jerry")
   {
      names[i] = "Bobby";
   }
   Console.WriteLine(names[i]);
}

With the above code sample, we can see that we are checking if the current iteration of the array is the name Jerry. If it does equal to Jerry, then we replace it with Bobby.

If we wanted to add a name to the array, it gets a bit more complicated, and would be best done with a List instead of an array.

Leave a Reply

Your email address will not be published. Required fields are marked *