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# 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

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV