Designed and Written by Michael Bartlett
This tutorial will introduce you to simple input and output functions available from the class Console, then take you on a guided tour of the different array types available in C#. Finally, we'll be looking at two famous decision structures that are ubiquitous throughout other languages: namely, if and switch.
You saw, from Listing 1x1, in the last tutorial that the basic C# executable program must have two parts. Firstly, whatever you write must be wrapped in a class. Secondly, the program must have an entry point, which is achieved through the method Main. There are now a further two things that need to be explained: firstly, the point of the Using System text. Using is a keyword that C# programmers are given so that they may reference pieces of code that have been grouped together into a logical area known as a namespace. If, for example, you were writing a computer game in C# and you wanted to package all your artificial intelligence routines together, you would put them all in a namespace, and probably call it something like 'AI'. Microsoft has packaged their console routines into the namespace called System. If you didn't include the text Using System, then you would have to write the following in order to access the console function, WriteLine:
The prefix 'System' will be needed if you don't reference it through 'using'![]() |
You will learn more about namespaces in a later exercise, but for now think of them as a logical way of referring to related classes. Namespaces also exist across source files, thus meaning you do not have to code all your related classes in the same C# source file (useful for large projects with multiple authors). In addition to understanding the Using keyword, you also need to know why we place the word static before the Main method. This is because any methods that have static in front of them, are said to pertain to their class instead of any instances (objects) of their class. When any executable program runs, there are no instances of its class active.
Listing 2x1 demonstrates this perfectly. As with all C# programs, there must be an entry point which, as we know, is the method Main. This function is wrapped inside the class Instance. When Main runs, the first thing it does is alert us to this fact, as shown in the code below that represents Listing 2x1's Main in its entirety. It then proceeds to create two instances of the class it is contained within, referencing one through the object type mentioned in the last tutorial, and one through a reference that is actually of type Instance. Object successfully references objects of other types because it acts like a general reference. Notice how the new operator is being applied. Taking the creation of the first instance variable, instance1, we can translate the code to the following: create a reference of type Instance called instance1 and then point it at a newly created object of type Instance. The (1) that appears after the class of which an instance is being created is simply the constructor being invoked (we'll talk about that next).
Main (taken from listing 2x1.cs)![]() |
From reading the code you'll also notice the implementation of the constructor, which is the method that has the same name as the class. As the code commenting states, this simply aids in initialisation, and is not mandatory. In this case the constructor prints a message telling you which instance of the Instance class it is. The keyword before the word, Main, specifies the return type for the Main method - for Listing 1x1 it was void, meaning there was no return type. For Listing 2x1, it is an integer. You can see the use of the keyword return inside the method's scope, which actually forces the return of some value. Even though main has not accepted any parameters in the code so far, I will be demonstrating later how it can. If you compile and run the program in the way described in Tutorial 1 you will get the following output:
>2x1![]() |
By now you should be comfortable with the concept of the Main method, the way that a static method works, and the general way a basic C# program is structured. You should see that all classes begin and end with curly braces, and that all statements end with a semicolon. Comments so far have taken the single line approach, but you can also comment out in a multi-line style in the following way:
The two ways of commenting in C#![]() |
Diving straight into listing 2x2, we finally can see an example of a program being influenced by user input. Once you have compiled this code, you will need to feed the program some user input (In this case your name) when you run it from the command prompt. The example below shows how to do this, but you should ignore the long path that proceeds it in the screen-capture, as this is just the path where the 2x2 program is stored on my machine.
>2x2![]() |
I have used my name, which will cause the program to output a hello message to me. Earlier on I mentioned that the Main method can accept parameters, and that is exactly what the code for Listing 2x2 is demonstrating. The string[] args simply indicate to the Main method that an array of strings are supposed to be entered from the command line when the program is run. args simply is the variable that holds the incoming data; we could have called it whatever we wanted. Arrays will be covered shortly. By inputting my name, I caused an array with a single element to be fed to the program. This element is accessed by using the array notation, [x], where x is the element you require; the first element is always [0], the second [1], the third [2], and so forth. If I had typed: ">2x2 Michael Bartlett" then the args array would contain two elements.
Outputting what the user enters is simple. Console.Writeline is used yet again to display the data. The '{0}' is a way to specify a marker to C# which says 'replace me with argument 0'. Also note for future referebce that \n is an escape character that signifies a new line. If the code was thus changed to read:
Code now prints out two arguments![]() |
..then running the program with two inputs would produce the result below. Listing 2x3 demonstrates how to retrieve input from the user through the Console.ReadLine() method. This program does pretty much the same as the last Listing, and is included to simply demonstrate the aforementioned method.
>2x2![]() |
Even though we have touched on the notation used to acces them, one data type that is yet to be explained in detail is the array. Arrays are useful for storing lots of variables of the same type. In the user interaction example, the array contained words, i.e. 'Michael' and 'Bartlett'. Listing 2x4 shows the creation and access of the three array types. These are:
As a programmer, you should be familiar with 1d and multi-d arrays. Their creation in C# is shown below:
Creating and populating 1d and multi-d arrays (taken from listing 2x4.cs)![]() |
Jagged arrays, however, are a little harder to understand; especially when you start declaring jagged arrays of multiple dimensions that point to arrays of multiple dimensions. Consider the code fragment below. This is declaring a 1d jagged array that contains 2 items. The indexes for these two items are zero and one. The code shows how the first element in the jagged array is pointing to a 1d array of 4 elements. The second element in the jagged array is pointing at a 1d array of 2 elements.
Declaring jagged arrays (taken from listing 2x4.cs)![]() |
When a jagged array is first declared, its type must be specified. Here are some examples of what certain types mean:
After its type is declared, the assignment operator is used, followed by the new keyword. Then the actual element sizes of the jagged array are stated, such as [4], or [5,2], etc. Then the dimensions of the array at which the jagged array points are filled in again, using the format [], [,] [,,,] etc . We do not actually specify the exact numbers, as this is done at a later time using the new keyword, because the arrays at which the jagged array points can have a different number of elements, but must all have the same dimensions:
Assigning arrays to elements of a jagged array (taken from listing 2x4.cs)![]() |
The next two Listings will demonstrate if and switch decision structures. As a programmer you should be familiar with if and switch statements, so this next section shouldn't take very long at all.
The general task description for Listing 1x5 and 1x6 is to prompt the user to enter a number between 1 and 10 inclusively, and then display one of the folowing messages:
We begin with the code for the if statement:
Using an if statement (taken from listing 2x5.cs)![]() |
Some of the comments had to be clipped in the code example above for sizing purposes. Following through from the Main method, then, the first thing that happens is that a variable of the value-type int is declared for the purposes of holding the number chosen by the user. A standard Console.Write line is then used to prompt for the user's input. We then store the contents of the user's input into our variable, but first we have to cast what they have typed from a string into an int. This is done via the Int32.Parse command.
We then use C#'s >= operator (greater than or equal to), and C#'s <= operator (Less than or equal to) to construct an if statement. if statements only execute the code inside their block if the statement inside the parentheses immediately following the if evaluate to being true. If the user types in 7, then the statement:
7 is greater than or equal to 1 and 7 is less than or equal to 5
won't be true. We use the else if keyword to test for additional statements being true. The else keyword is a way of saying "If none of the above statements have evaluated to true, then execute my code block" In this case, we have two scenarios (between 1 and 5, and between 6 and 10) which we will represent with an if and an else if. If the user hasn't selected a number in the correct range, we can implement an else to catch that possibility. Here is the program in its glory:
>2x5![]() |
Listing 1x6 begins in exactly the same way as Listing 1x5, except that a strange line appears before the program prompts for and accepts the user's input:
A label that can be used by goto statements![]() |
This, as the title and code commenting suggests, is a label. Labels are used as markers for specific places in your C# code, and are identified by a word followed by a colon. At any time, you can jump to this point in the program by using a goto statement. To demonstrate this, I decided to alter the program in Listing 2x6 so it operated slightly differently from the one in Listing 2x5. The new addition is to make the program jump back to the label if the user does not enter a number in the two legal ranges. This means that it will execute everything from the label onwards again, and thus keep asking the user to enter a number between 1 and 10 until they finally do so. In Listing 2x6, the if block has been replaced by a switch block as shown below:
A switch statement (taken from listing 2x6.cs)![]() |
The switch statement is the point in the program where the variable whose value will cause a branch in your program is fed in. In this case, we are telling C# that yourNumber is about to do this. Once this is done, we simply code up the functionality required for each of the variable's values that causes something to happen. This is done by using the case keyword and then specifying the criteria to trigger the code-branch. A colon is then used, followed by the actual code itself. When we are happy with what we have coded, we use the break keyword so that the program jumps to the end of the switch block. If you do not use break then C# will go ahead and execute the next case even if its value does not match the criteria. This is useful, as it saves you having to code up the same thing over and over again for a range of identical cases.
In our code, we simply have left 1,2,3 and 4 blank. This means that if the user types anything between 1 and 5, it will always end up in case 5, because the other values do not have a break command. In case 5, we add a break so that C# does not start executing code in cases 6-10. As with the else statement we saw in Listing 2x5, default: does the same thing here. The only difference is that the number entered is out of range, so we are going to leap directly back to the label defined earlier by using a goto keyword, followed by the label's name. Here is Listing 1x6 in action:
>2x6![]() |
[OVERVIEW] | [TUTORIAL 1] | [TUTORIAL 2] | [TUTORIAL 3] | [TUTORIAL 4] |