Skip to main content

C# Basic Array Tutorial [Beginner]





Arrays are not complicated, and they are definitely not something that is really advanced. But, everyone has to start someplace, and today we are going to glance over some of the main properties of Arrays. Mainly, we are going to create, fill, sort, and display some arrays of all kinds. It is not going to take a lot to explain it, but there are several different ways to go about doing some of these steps. So let's get to it.

Now there are several characteristics that separate them from other collections. First off, they are made up of only one data type (e.g. integers or strings). This means you cannot have an array with an integer for one element, and a string for another. Secondly, and probably most importantly, arrays have a defined size. Once you set this size, it cannot be changed. So if you have an array with 10 elements, it will always have 10 places to store data. That data can change of course, but you can never fit another element inside the array itself. Lastly, arrays in most languages are zero indexed, meaning that the first element is numbered 0 rather than 1.

In C#, to create an array you must declare its type followed by brackets, then supply its name. Such as:
int[] ints;
 
For those who may know a little about what is going on, you will notice that we did not define a size. This is because in C# you declare an array, then assign its size and values later on. You can use this fact to "initialize" the array later on, but you can also set up the array at creation as well. For example, to create an empty 10 element integer array:
int[] ints = new int[10];
 
This will create an empty 10 element integer array. It is ready to take on some data. There are actually several ways to accomplish filling this array with data. The most simple of the solutions would be to set the data at array creation. All you have to do is supply a comma-separated list enclosed in curly braces:
int[] ints = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
This code is creating an array just like before, except that the elements are filled in with the data provided in the curly braces at the end. But, we can also use a loop to fill in our array. On top of that, there are several loops in C# that can get the job done. For now, let's use the for loop, which gives us the most basic functionality:
for (int i = 0; i < ints.Length; i++)
{
  ints[i] = i;
}
 
This is looping through each element, setting each integer to its current position in the array. So integer 0 is set to 0, integer 1 is set to 1, and so on. Using the Length property ensures that the loop will work no matter what size we specified the array to be.

Looping through an array can be useful for assigning values, but using a foreach we can iterate through those values. It would be more difficult to assign values with a foreach, but it does allow us to display or even make calculations. The great thing about a foreach is that you just give it a datatype, variable to hold the values, and an array and it will iterate through it. For example:
int total = 0;
foreach (int i in ints)
{
  total += i;
}
 
All this will do is add the numbers in the array, storing the total in the variable total. This loop will, of course, work for any size array we can throw at it, as long as it is an array of integers. But, a more practical use would be to display the contents.

A Small Project

 

What we are going to do now is create an array, fill it with random contents, then sort it. We are going to be using the most basic built-in functionality to sort our array, but it is still pretty powerful and still pretty neat. Before we sort, however, we need an array to fill with stuff. For this example, we are gong to be using an integer array again.

For this example, we are going to need 2 variables: an array and a random number object. We are going to use a 10 element array and a random number object to help fill in the data:
int[] ints = new int[10];
Random rand = new Random();
 
Random is a class built into .NET, and allows us to create random integers really, really easily. Basically all we have to do is call a method inside our rand object to get that random number, which is nice. So, inside our loop, we just set each element to the results of that method:
for (int i = 0; i < ints.Length; i++)
{
  ints[i] = rand.Next(1000);
}
 
We are essentially filling our entire array with random numbers here, all between 0 and 1000. At this point all we have to do is display the contents for the user, which can be done with a foreach loop:
foreach (int i in ints)
{
  Console.WriteLine(i.ToString());
}
 
No points to guess what we missed. Yes, this code will display the contents of the array, but we skipped sorting it first. In order to sort the contents, we are going to use a method in the Array static class. This class contains a sort method that takes in one argument, the array to be sorted. We add this method call after we fill the array, but before we display, thus giving us the final outcome:
int[] ints = new int[10];
Random rand = new Random();

for (int i = 0; i < ints.Length; i++)
{
  ints[i] = rand.Next(1000);
}

Array.Sort(ints);

foreach (int i in ints)
{
  Console.WriteLine(i.ToString());
}

/*
Output:
294
312
522
663
707
766
875
920
943
975
*/
 
The sort method sorts from smallest to largest by default, and for this example that is ok. One of the coolest features of this built-in sorting is that it works with string arrays as well, sorting alphabetically:
string[] strings = new string[5]{
    "George",
    "Becky",
    "Albert",
    "Sam",
    "Crystal"
  };

Array.Sort(strings);

foreach (string s in strings)
{
  Console.WriteLine(s);
}

/*
Output:
Albert
Becky
Crystal
George
Sam
*/
 
As you can see, our array is sorted quite nicely. This basic sorting method can be used with any sort of basic array, even floating point numbers.

Arrays are not used too often anymore, do to their non-dynamic size, but they still have their place. It is also always good to know what loops you can use them in, and what good using such loops will do. But it is always a good idea to know how to sort them.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as