Language Author: Rich Tebb Company: Content Master Ltd Introduction The Visual Studio Express family provides a free, lightweight, and easy-to-learn suite of programming tools that are aimed at the hobbyist, novice, and student developer. Many people in this category will not have had any formal training in computer science, and indeed they may not have any programming experience at all. f you fall into this category, don!t worry " this guide is for you# This beginner!s guide is designed for people with little or no prior $nowledge of computer languages, who want to learn to program by using the %& language. f you have some previous programming experience, maybe in another language or from a few years ago, then you may also find this guide useful. f you are a professional developer, or you are already s$illed in one or two programming languages, then you will probably not have much to learn from this document. 'hether or not you have programmed before, you should already be familiar with computers before reading this guide. t assumes that you can perform simple tas$s li$e starting a program, and that you are familiar with navigating around your computer by using 'indows Explorer. So what will you learn by reading through this guide( 'ell, the most important thing you can learn is that )rogramming is *un# t!s a great feeling of satisfaction when you finish a program and it does what you want " whether your program is a computer game that you!ve invented, or it controls a robotic device, or serves any other purpose that you can imagine. There may be obstacles along the way " li$e any challenge, programming can present difficulties " but when you see your finished program wor$ing, you can ta$e pride in the fact that you overcame the problems, and converted your imagination into reality. +s well as " we hope " learning that programming is fun, in this guide you will learn how to create a simple program. ,our program will include basic but essential programming techni-ues such as methods, variables, controlling program flow, and how to create your own classes " the fundamental structural units of a %& computer program. +lthough you will be using Visual Studio tools to create your program, this is not a guide to the full features of Visual Studio. ,ou can learn more about how to use Visual Studio in other MS./ guides. What is Programming? %ontrary to popular belief, computers are not clever. 0eft to itself, a computer doesn!t do anything at all " it won!t show the time, or display what you type on the screen, let alone play a video game. The reason that computers are such useful tools, and give the appearance of cleverness, is that they follow instructions, very accurately, very repetitively, and very -uic$ly. *or example, when a computer displays a cloc$, it does so because it has instructions for how to draw every color and tic$ mar$ in the cloc$ face, and every line in the cloc$!s rotating hands, onto the computer screen. )rogramming is the act of giving instructions to a computer so that it $nows how to perform an action. *undamentally, these instructions are a series of numbers " to a computer, everything is numbers " in a $ind of code where different numbers represent different instructions. The good news is that programmers don!t have to learn all these numbers 1the 2machine code!3, because they can write their instructions in a more intuitive form, and then have the computer convert these instructions into machine code. The intuitive or human-readable form of instructions is called a computer language. 0i$e languages in the real world, there are do4ens of computer languages. Some are for speciali4ed tas$s and others are more general-purpose. 'hat all programming languages have in common is that they enable programmers to create instructions for a computer without having to learn the computer!s numeric machine code. n this guide you will learn about %& 1pronounced 2%-sharp!3, which is a general-purpose language that you can use to program on the Microsoft ./ET platform. ,ou can program in %& by using Visual C# 2005 Express Edition, which is available as a free download from the Microsoft 'eb site at http566msdn.microsoft.com6express6. The hands-on examples in this guide assume that you have already downloaded and installed Visual %& 7889 Express Edition. Lesson 1 !our "irst #$ello World% Program The first program that students traditionally write when they learn a new language is a program that simply writes a message to the computer screen which reads :;ello, world#< ,ou can create a 2;ello 'orld! program by following these instructions5 =. >pen Visual %& Express Edition " on the &tart menu, point to 'll Programs, and then clic$ (icroso)t Visual C# 2005 Express Edition. 7. >n the "ile menu, clic$ *e+ Pro,ect. n the Visual &tudio installed templates list, clic$ Console 'pplication, enter (-"irst'pplication in the *ame box, and then clic$ ./. ?. Visual %& will create an outline program for you, and display the code for that program in the code window. @. nsert the following line of code 1underlined below3 into the outline program in the code window5 using System; using System.Collections.Generic; using System.Text; namespace MyFirstApplication { class Program { static void Main(string! args" { Console .WriteLine( "Hello, world!" ); # # That!s it# ,ou!ve Aust written your first program in %&. 0et!s run the program to see what happens. 0unning the Program >n the 1e2ug menu, clic$ &tart Without 1e2ugging 1or Aust press Ctrl3"53. + command prompt window appears that loo$s li$e this5 )ress a $ey to dismiss the window. The program you Aust wrote might not seem too exciting, but -uite a few things happened when you pressed %trl-*9. =. Visual Studio detected that it needed to 2build! the program, because this is the first time the program has been run. 7. To build the program, Visual Studio invo$ed a special $ind of program called a compiler, which understands the %& language and $nows how to convert it into machine code. ?. The compiler converted the 2source code! for your program 1which is Aust a plain text file containing the %& code you wrote3 into machine code which the computer can understand. @. >nce the compiler finished, Visual Studio too$ the compiler!s output " which is your program " and ran that program. Because your program is a console application, Visual Studio actually launched a console window and ran the program inside that window. 9. >nce your program had written :;ello, 'orld#< on the screen and finished, Visual Studio displayed the :)ress any $ey< message so that you could see what your program had displayed before the window closed. ,ou could do all these steps yourself, of course, but it!s much easier to use the Visual Studio ntegrated .evelopment Environment 1.E3 to do them on your behalf. ;owever, it!s important that you understand what!s going on behind the scenes. ' Closer Loo4 at the Program Code /ow let!s examine the code and see how it wor$s. +lthough you only added a single line of code to the outline program that Visual Studio generated, the whole program code is important so that the compiler can ma$e sense of that single line. The code begins with a few lines that introduce the parts of the ./ET framewor$ that you will be using in the program. 'e!ll see how these wor$ shortly. using System; using System.Collections.Generic; using System.Text; The next few lines specify that you are creating a class called Program inside a namespace called (-"irst'pplication. + class is a container for your code. ,ou must have at least one class in a program, but most programs have several. %lasses are a fundamental part of programming in %&, so we!ll loo$ at them in more detail later on. + namespace is a way of grouping several classes together. The full name of the Program class is actually MyFirstApplication.Program, because it!s inside the MyFirstApplication namespace. namespace MyFirstApplication { class Program { /ote the funny punctuation mar$ 12C!3 below the n in namespace and the c in class. These mar$s are $nown as curl- 2rac4ets or 2races, and they mar$ the beginning and the end of a bloc$ of code. *or every opening brace 12C!3 there must be a closing brace 12D!3 to denote the end of the bloc$ of code. 1To help you get this right, if you put the cursor to the left of a brace in the code window, Visual Studio highlights both matching braces3. The other thing to note here is that everything between the two matching braces is indented. This is Aust a convention to help you read the program more easily " the compiler doesn!t care if your code is pretty or not# n fact, you could leave out all the line brea$s and write your program on a single line " but you might have trouble understanding what you!ve written. The next line declares a method called (ain. Methods are very important in %& - they are bloc$s of code that do most of the wor$ in a program. + class can have multiple methods " you can thin$ of methods as actions that your class can perform. 'e!ll ta$e a deeper loo$ at methods later, but for now you need to $now that the Main method has a special place in a program, because it!s where the program starts running. ,ou can write your methods in any order in the source code, but the Main method will always be where your program starts. static void Main(string! args" { *inally, we have the code which actually writes the message to the screen. n this case, we use a class called System.Console, which is part of the ./ET *ramewor$. nside the System.Console class there is a method called $rite%ine, which writes a message to the console. +s an aside " how is it that the class is called System.Console but we Aust call it Console( 'ell, remember the first line of the program5 using System; That was an instruction to the compiler that your program will be referring to classes within the System namespace by an abbreviated name, by leaving off the namespace at the start. The three namespaces that Visual Studio specified in the outline program " System, System.Collections.Generic, and System.Text " are commonly used namespaces. ,ou are only using the System namespace at the moment in this program, so the other two statements are redundant " unnecessary but harmless. >ne small but important point to notice is the semi-colon at the end of the line. ,ou must put a semi-colon after each statement to indicate the end of the statement. +s mentioned earlier, the %& language ignores line brea$s, so you need to add a semi-colon to show the end of each statement. Console.$rite%ine(&'ello( )orld*&"; # # # Lesson 2 5sing (ethods and Varia2les +s you saw above, all programs must define a method called Main, which is the starting point for the program. But you can also add other methods. Esually you would create a method when you want to perform the same set of instructions, perhaps with slight differences, several times in a program. 6he &a-$elloWorld (ethod 0et!s have a loo$ at how you would create a method. n the source window, right after the closing brace of the Main method, add a newline and then add the following code underlined below5 using System; using System.Collections.Generic; using System.Text; namespace MyFirstApplication { class Program { static void Main(string! args" { Console.$rite%ine(&'ello( )orld*&"; # static void SayHelloWorld() { Console .WriteLine( "Hello, World!" ); } # # ,ou can see that the Say'ello$orld method has some similarities with the Main method. They both begin with static void, then the name of the method, then some parentheses. The contents of the Main method and the Say'ello$orld method are identical " they both call Console.$rite%ine. The main difference is that in the Say'ello$orld method, the parentheses are empty, but we!ll loo$ at that in a minute. Before we do so, let!s see how this method wor$s in action. Modify the Main method so that it calls the Say'ello$orld method instead of calling Console.$rite%ine, as follows5 =. n the Main method, delete the line that reads Console.$rite%ine(&'ello( $orld*&"; 7. +dd a line that reads Say'ello$orld("; /ow run the program without debugging 1Ctrl3"53. There!s no visible change between the output of the original program and the new version. The only difference is that the Main method no longer writes to the console itselfF it calls a different method to write to the console on its behalf. 6he &a-$ello6o (ethod The Say'ello$orld method doesn!t add much to your program " it!s Aust a way of illustrating how you can create and call a method. /ow let!s create a different method, a bit more useful this time because it!s slightly more flexible. +dd the following code underlined below, right after the Say'ello$orld method5 using System; using System.Collections.Generic; using System.Text; namespace MyFirstApplication { class Program { static void Main(string! args" { Say'ello$orld("; # static void Say'ello$orld(" { Console.$rite%ine(&'ello( $orld*&"; # static void SayHelloTo( string toWo!) { string !essage " "Hello, " # toWo!; Console .WriteLine(!essage); } # # ,ou can see the obvious similarities between this method and the Say'ello$orld method. But there are some interesting differences, too. Before we examine them, let!s see this method in action. Modify the Main method by adding the following lines right after the line that calls Say'ello$orld5 Say'elloTo(&+ric&"; Say'elloTo(&Sandra&"; Gun the program without debugging. ,ou should see the following output5 ,ou can probably see the gist of what!s going on here. The Say'elloTo method allows you to specify to whom to say hello, by putting the name of the person as a parameter when you call the method 1you can thin$ of a parameter as an input to a method3. 'e put parenthesis :1< and :3< around the parameters after the method name. 3 'ello( Sandra 'ithin the Say'elloTo method, we don!t $now what the actual value of the parameter will be when someone calls the method. n this program, the values :Eric< and :Sandra< are usedF but you could use other values instead. The Say'elloTo method needs a way of handling the value without $nowing what the value actually is. To get round this, %& enables us to create a 2slot! for the value, and give that slot a name. n this method, we!ve called the slot to$,om. The proper term for the slot is a 7aria2le, so called because the slot!s value can vary. Varia2les and 1ata 6-pes Variables are very important features in %&, or any other programming language. + variable is where you can store information and retrieve it 1in computer terms, a variable refers to an area of computer memory where the variable!s value is stored3. ,ou must give the variable a name, which you then use when storing or retrieving information from that variable. The name you use for a variable can be anything that you choose, subAect to a few restrictions5 Variable names can only contain letters, numbers, and the underscore 2H! character. They cannot contain spaces or punctuation. Variable names cannot start with a number. Variable names must not clash with other variable names " you cannot use a variable name if it!s already in use in the same part of the program 1this restriction isn!t as severe as it may seem, for reasons that will become apparent3. To help the computer set aside the right amount of memory for the variable, %& insists that you specify a data t-pe in addition to the variable name. + data type, as the name implies, denotes what type of data the variable will hold. There are many different data types in %&, and you can create your ownF but some examples of the most commonly- used types are5 1ata t-pe 1escription Example int +n integer, @ bytes in si4e, which can hold a value between -7,=@I,@J?,K@J and 7,=@I,@J?,K@I @? -yte +n integer, = byte in si4e, which can hold a value between 8 and 799 =7I decimal + number with decimal places, which can hold a value between L=.8M=8 -7J
and LI.NM=8 7J =8NKK.79N7 string + se-uence 1or :string<3 of characters O;ello, 'orld#O c,ar + single character PhP -ool + logical value which can be either true or false true Before you can use a variable, %& insists that you declare it. This means that you must specify the type and the name of the variable, so that the program $nows what you are tal$ing about before you start to use it. + declaration can be a simple statement such as int x; This declares a variable called x which will contain values of integer type. ,ou can optionally assign a value to the new variable when you declare it, as follows5 int y . /0; This statement declares a variable called y, as above, and then initiali4es it with a value of @?. %& imposes an important restriction on your use of variables. t does not allow you to store a value that has one data type in a variable of a different data type. This can be a little confusing at first, because you can!t do some things that seem perfectly obvious. *or example, here is some code that declares two variables and assigns values to those variables. int my1nteger . /0; string myString . &/0&; t might seem obvious that my1nteger and myString have the same value, but in %& these variables have completely different values. n fact, they have completely different types, so you couldn!t even compare my1nteger and myString to see if they were the same value# my1nteger can only contain values of type nteger, while myString can only contain values of type String. So even though @? is an integer value, when we put -uotes 1OO3 around it, Visual %& treats whatever is between the -uotes as a String value. 0et!s have a loo$ what happens when you try to mix data types. %reate a new method in the program by adding the following code after the Say'elloTo method5 static void $rong(" { int my1nteger; string myString . &/0&; my1nteger . myString; # This method attempts to assign a string value 1myString3 to an integer variable 1my1nteger3. %& does not allow this, and you can!t build the program when it contains this $ind of error. The following steps show what happens when you try5 =. )ress Ctrl3"5 to run the program without debugging. 7. + dialog box appears that informs you that there were build errors. %lic$ *o to indicate that you do not want to run the last successful build. Below the code window, Visual Studio displays the Error 0ist window5 The Error 0ist window contains information about the build errors reported by the compiler. n this case, the error description states5 %annot implicitly convert type PstringP to PintP This message = indicates that the compiler tried to assign the value of one variable to another variable, but was unable to do so because one is a string variable and the other is an int variable. /ow you have seen what happens when you try to mix data types, you should delete the $rong method from the program. Gun the program again to chec$ that it wor$s correctly. 6he &a-$ello6o (ethod 0e7isited /ow you understand what a variable is, let!s ta$e another loo$ at the Say;elloTo method to get a deeper understanding of how it wor$s. static void Say'elloTo(string to$,om" { string message . &'ello( & 2 to$,om; Console.$rite%ine(message"; # The first line is the method header, and tells us the name of the method, along with what parameters it expects a caller to provide. n this case, the Say'elloTo method expects a parameter with a string type, which is identified by the name to$,om. +fter the header is the opening of the curly brac$ets that enclose the body of the method. The first statement in the method body declares another string variable, called message, and assigns a value to message that consists of the string O;ello, O Aoined to the value of the to$,om variable. The plus sign :Q< operator is used to append string values together. So if the caller of the method passes a parameter of OEricO when it calls Say'elloTo, then the variable message will have a value of O;ello, EricO after this statement has executed. The second statement is our old friend Console.$rite%ine. There is a subtle difference here from how we!ve used it previously, however. /otice that there are no -uotation mar$s around message. This is because we are passing the value inside the message variable, not the actual string OmessageO, as a parameter to the Console.$rite%ine method. = The compiler error message 2%annot implicitly convert type! is an unusual turn of phrase. The choice of words hints at two implications5 R )erhaps it is possible to perform an explicit conversion from string to int( This is indeed the case " we could explicitly call the 1nt.Parse method to convert from a string to an int. R +lthough the compiler cannot implicitly convert between string and int, perhaps there are some cases where it can perform an implicit conversion( This is also true " for example, the compiler will implicitly convert a -yte value to an int value, because they are similar data types. .on!t worry too much about data type conversion " it is an advanced topic. The important thing to remember is that, as a general rule, you must not mix together variables with different data types. To see the effect of this subtle but important difference, change the second statement so that it reads Console.$rite%ine(&message& "; - including the -uotation mar$s - and run the program again without debugging. This time, the output from the Say'elloTo method is not what we intended5 Because of the enclosing -uotation mar$s, the compiler has used the literal string OmessageO instead of the value of the message variable as a parameter to Console.$rite%ine. 'e don!t want Say'elloTo to wor$ li$e this, so go ahead and remove the -uotes around message, then run the program to chec$ it!s wor$ing correctly. (ethods 6hat Produce .utput Values So far, the methods you have written simply perform some actions on behalf of your program. By using variables and parameters, a method can perform the same action with different data. But you can also write methods that calculate a value and send that value bac$ to the caller. +dd the following code right after the Say'elloTo method5 static string CalculateGreeting(string to$,om" { string message . &'ello( & 2 to$,om; return message; # There are two important differences between this method and the Say'elloTo method. The first is in the method header " instead of saying static void it says static string. This tells the compiler that the CalculateGreeting method produces an output value which has a string data type. The previous methods used void, which indicates that there is no output value from those methods. The other difference is in the last statement in the method, which reads return message; The return $eyword indicates that the method should return a value to the caller " in this case, the value to return is the contents of the message variable. The value returned by a method is called the return 7alue or the result. 'hat the CalculateGreeting method does is to perform a calculation, and then send the result of the calculation bac$ to the code that called the method. /ow modify the first statement of the Say'elloTo method, so that it reads string message . CalculateGreeting(to$,om"; This statement is a method call, Aust li$e when you called Say'elloTo from the Main method. The difference is that the program ta$es the result of CalculateGreeting and assigns that value to the message variable. Gun the program to chec$ that it wor$s, and that you still see the same console output as before. Lesson 8 Controlling Program "lo+ So far, our program has operated in a straightforward se-uential manner. The program starts executing in the Main method, and proceeds until the end of that method, with a couple of diversions into other methods along the way. Those methods, in turn, simply start on the first statement of the method, and carry out every statement until they reach the end of the method. 'hen each method ends, the program returns to the piece of code that called that methodF and when the Main method ends, the program ends. Conditional 9eha7ior and Expressions But what if we want to ma$e the program behave in a slightly different way under certain conditions( This is $nown as conditional behavior, because the behavior of the program depends on specific conditions being met when the program is running " :if this condition is true, then do this, else do that<. +s an example, let!s change the CalculateGreeting method so that it gives a different greeting message depending on the person whom it is greeting. Geplace the existing CalculateGreeting method with the following code5 static string CalculateGreeting(string to$,om" { string message; i3 (to$,om .. &+ric&" { message . &'i( & 2 to$,om; # else { message . &'ello( & 2 to$,om; # return message; # n this version of the CalculateGreeting method, we use an i3 statement to test the value of to$,om. f the value of to$,om is e-ual to OEricO then the method returns one greeting, otherwise it returns a different greeting. By now it will be easy for you to guess what the output will be when you run the program5 n the i3 statement, notice that there is a double e-uals sign " it!s not a misprint. n %&, the single e-uals sign is $nown as the assignment operator, and you use it when you want to assign the value of a variable. The double e-uals sign is called the e:ualit- operator, and you use it when you want to test two values to see if they are e-ual. There are a few other comparison operators in %&5 .perator 1escription SS E-uality. The expression has the value true when the left hand and right hand values are e-ual, 3alse otherwise. #S ne-uality. The expression has the value true when the left hand and right hand values are not e-ual, 3alse otherwise. T 0ess than. The expression has the value true when the left hand value is less than the right hand value, 3alse otherwise. U Vreater than. The expression has the value true when the left hand value is greater than the right hand value, 3alse otherwise. TS 0ess than or e-ual. The expression has the value true when the left hand value is less than or e-ual to the right hand value, 3alse otherwise. US Vreater than or e-ual. The expression has the value true when the left hand value is greater than or e-ual to the right hand value, 3alse otherwise. 0et!s Aust pic$ up on a point there. 'hat exactly does :the expression has the value true< mean( 'ell, to use the example from the CalculateGreeting method, the underlined part is the expression5 i3 ( toWo! "" "$ric" " 'hen the program runs, the expression is evaluated 1this is a computer-spea$ term for 2wor$ed out!3 and the result determines which of the following code bloc$s is executed. f the to$,om variable has the value OEricO, then the expression to$,om .. &+ric& evaluates to true. n this case, the program executes the code bloc$ following the i3. f to$,om has some other value, then the expression evaluates to 3alse, and the program s$ips the i3 code bloc$, and executes the code bloc$ following the else. n %&, you don!t actually need to provide an else section. f you omit this section, then the program will continue execution after the i3 code bloc$. These $inds of expressions that evaluate either to true or to 3alse are called 9oolean expressions. They are very common in computer programming, which is why they have a special word to describe them. The -ool data type, introduced above, holds Boolean values. Looping and Iteration )art of the power of computers is that they can perform tas$s repetitively, and for that we need a way of telling our program to repeat itself. The technical term for this repetitive behavior is looping. + loop is a series of instructions that is repeated until a certain condition is met. Esually a loop contains a Boolean expression that determines whether to continue looping or to stop. 0et!s loo$ at an example of a loop. 'e will change the program so that it repeatedly as$s for a person!s name, and then displays a greeting, until someone Aust presses the Enter $ey. Modify the Main method so that it loo$s li$e this5 static void Main(string! args" { Console.$rite(&Please enter your name4 &"; string name . Console.5ead%ine("; ),ile (name *. &&" { Say'elloTo(name"; Console.$rite(&Please enter your name4 &"; name . Console.5ead%ine("; # # Gun the program. 'hen prompted, enter a name and press Enter " you can try this as many times as you li$e. 'hen you get bored, Aust press Enter without typing a name. .epending on how -uic$ly you get bored, the output will loo$ something li$e this5 The first point about our new Main method is that it uses two methods that we haven!t used before5 Console.$rite and Console.5ead%ine. Console.$rite is almost identical to Console.$rite%ine, except that it doesn!t add a line brea$ after it has written the text. Console.5ead%ine is a somewhat new concept, because it reads from the console rather than writing to it. 'hen your program calls Console.5ead%ine, the program pauses until the user presses the Enter $ey. The return value from Console.5ead%ine is a string containing the text that the user typed before pressing Enter. The important change in the Main method is the use of the ),ile loop. This is how the ),ile loop wor$s5 =. +t the start of the loop, the program evaluates the ),ile condition, which is a Boolean expression li$e the ones you have already seen. 7. f the condition is true, then the code bloc$ is executed, otherwise the program s$ips over the code bloc$ and continues from there. ?. 'hen all the statements in the code bloc$ have executed, the program loops bac$ to the top of the ),ile statement and evaluates the conditional expression again. n our loop, the conditional expression will be false once the user presses Enter without typing anything else. n this case, the return value from Console.5ead%ine is an empty string, which is represented in %& by two double--uotes with nothing in between. >nce this happens, the program s$ips over the code bloc$ and continues with the next statement. n summary, a ),ile loop repeats while an expression continues to be true. The loop will exit the first time the expression evaluates to false. 6he )or Loop The ),ile loop is useful when you want to repeat a code bloc$ for an uncertain number of times. 'hat about when you already $now how many times you want to repeat the code bloc$( The tool of choice in this situation is the 3or loop, which you use to repeat the loop for a certain number of times. 0et!s say that we want our program to greet three people only, no more and no less. ;ere!s how you should modify the Main method to loop three times5 static void Main(string! args" { 3or (int i . 6; i 7 0; i22" { Console.$rite(&Please enter your name4 &"; string name . Console.5ead%ine("; Say'elloTo(name"; # # The 3or loop loo$s a little more complex than the while loop, because there are three parts to the 3or clause, separated by a semi-colon. The diagram shows the parts of a 3or clause, using the example above. ;ere!s how it wor$s5 =. The initiali4er statement is executed only once, at the start of the loop. t declares an integer variable called i and assigns it the value 8. 7. The condition is a Boolean expression that is evaluated each time the loop is repeated 1including the first time3, Aust li$e in a ),ile loop. ?. f the condition evaluates to true, then the code bloc$ is executed. @. *inally, the iterator statement is executed after all the statements inside the 3or code bloc$, each time the loop repeats. 1The statement i22 is an instruction to add = to the variable i. So each time through the loop, the value of i will be increased by one. t is e-uivalent to the expression i . i 2 83. n fact, the 3or loop is Aust a shorthand for a ),ile loop with a few frills. ;ere!s the same loop, written using a ),ile statement5 int i . 6; ),ile (i 7 0" { Console.$rite(&Please enter your name4 &"; string name . Console.5ead%ine("; Say'elloTo(name"; i22; # 0ooping the right number of times can be confusing " even for experienced programmers# 0et!s wal$ through the example and see how it ensures we only execute the main code bloc$ three times. *ocus on the condition expression 1i 7 03, and how the value of i changes each time through the loop. The table below shows the value of the variable i each time the condition is evaluated5 Value o) i *otes 8 >n the first pass through the loop, the initiali4er statement has Aust assigned the value 8 to i. The expression i 7 0 is true, therefore the loop goes on to execute the main code bloc$. = The next time the condition is evaluated, the main code bloc$ has been executed and the iterator statement 1i223 has been executed immediately afterwards. The variable i has the value =, therefore the condition i 7 0 is true, so the loop continues. 7 >n the next occasion that the condition is evaluated, the main code bloc$ has by now been executed twice. +s on the previous occasion, the loop continues, because i has the value 7. ? >n the next pass, the main code bloc$ has been executed three times in total. This time, because i has the value ?, the condition i 7 0 is false, so the loop ends. ,ou might wonder why we start counting at 4ero rather than one. n the above example, we could achieve the same result if we started at one, and replaced the condition with i 7. 0. The main reason in the above example is convention " in %& it is traditional to start counting at 4ero. There are other reasons too, which you will discover as you learn more about %&. Lesson ; Creating !our .+n Classes 'ay bac$ when we loo$ed at the original ;ello 'orld program, you may remember that the outline code created by Visual Studio loo$ed li$e this5 class Program { ... t,e program code goes ,ere! ... # +t that point, we s$immed the concept of classes by saying that they are a container for code. This is true as far as it goes, but there is far more to classes than merely containing code. %lasses are fundamental to programming in %&, because they enable you to organi4e your code in a sensible way. Wust as, in a museum, the curators group related items together and display them in the same roomF in the same way, you can use classes to group together related parts of your code. The reason in both cases is the same " so you can find your way around. n a small program li$e our ;ello 'orld program " Aust li$e in a small museum " you can find what you want Aust by loo$ing through everything, even if there is no organi4ation. But as you write bigger and more complex programs, you will find that the way you organi4e your code helps you to find what you want. So it is important to understand how you can add structure to your programs by using classes. 6he <reeting Class +lthough classes can help you to structure your program, there is no right or wrong way to do so. To use the museum analogy, a curator might choose to organi4e the collection in chronological order, or by the type of artwor$ " paintings in one area, sculptures in another " or even alphabetically. Some ways of organi4ation are perhaps more useful than others, and many boo$s have been written on how best to organi4e a program, but ultimately the decision is with the design team. This guide does not attempt to discuss program designF but you can learn how to create and use classes in %&. n this section, you will create a class that manages greetings, which will replace the Say'elloTo method that you wrote earlier. To create the Greeting class, use the following steps5 n Visual Studio, in the Solution Explorer window, right-clic$ the (-"irst'pplication proAect, point at 'dd, and then clic$ Class. 9. n the *ame box, type <reeting=cs, and clic$ 'dd. Visual Studio creates a new file called Vreeting.cs, with the outline code for the Vreeting class, which loo$s li$e this5 using System; using System.Collections.Generic; using System.Text; namespace MyFirstApplication { class Greeting { # # Except for the absence of a Main method, this is remar$ably similar to our original Program class. 'e have defined a class called Greeting, although it has no contents at the moment. To rectify that, modify the Greeting class so that it loo$s li$e this 1be careful to replace only the Greeting class and not the whole file35 class Greeting { private string 9recipient; pu-lic Greeting(" { 9recipient . &Stranger&; # pu-lic void :isplay(" { string message . &'ello( & 2 9recipient; Console.$rite%ine(message"; # pu-lic string 5ecipient { get { return 9recipient; # set { 9recipient . value; # # # Before we examine the Greeting class in detail, let!s see it in action. Vo bac$ to the Program class 1clic$ on the Program=cs tab at the top of the code window3, and modify the Main method as follows5 static void Main(string! args" { Greeting t,eGreeting; t,eGreeting . ne) Greeting("; t,eGreeting.5ecipient . &+ric&; t,eGreeting.:isplay("; # /ow run the program without debugging. The output loo$s li$e this5 n terms of what the program does, there!s not much change here from what we!ve seen before. n terms of how the program does it, however, this is a whole new ball game. 5sing the <reeting Class Before we examine the Greeting class itself, let!s ta$e a loo$ through our new Main method in the Program class. The way that we use the Greeting class introduces some important new concepts. Greeting t,eGreeting; The first statement declares a variable called t,eGreeting, much li$e we saw earlier. The difference between this declaration and the ones we saw earlier is that the type of the variable is Greeting, rather than int or string. +s you learned earlier, this means that the variable 2slot! can only hold a Greeting value. The slot is initially empty, so the next line puts something in the slot5 t,eGreeting . ne) Greeting("; This statement creates a new Greeting obAect and stores it in the t,eGreeting variable. 'hat this means, and why you must do this, re-uires a bit of bac$ground explanation. 'hen you defined the Greeting class in Vreeting.cs, you did not actually create a Greeting at all. The class definition simply describes a conceptual Greeting. t is a blueprint, rather than the airplane itself. f you li$e, it tells the compiler : am defining a class of obAects in my program, called GreetingF and this is what a Greeting obAect would loo$ li$e and how it would behave.< To use one of these conceptual Greeting obAects, you must create a new obAect based on the Greeting blueprint. This new obAect is an instance of the Greeting class, and the process of creating the obAect is called instantiation. n %&, you use the ne) $eyword to instantiate a class. t,eGreeting.5ecipient . &+ric&; /ow we have created a Greeting obAect, we can start to use it. +s you will see below, we have defined a propert- of the Greeting class called 5ecipient. The 5ecipient property represents the recipient of the greeting. n this case, we want to greet Eric, so we set the 5ecipient property accordingly. t,eGreeting.:isplay("; This statement calls the :isplay method on the t,eGreeting obAect to display the greeting on the console. The :isplay method is also defined in the Greeting class. ,ou may be wondering why you use the t,eGreeting variable when you access the :isplay method. +fter all, when you accessed the Console.$rite%ine method, you didn!t need to create an instance of the Console class. The answer is that, when you define a class, you can define a method by using the static $eyword " as we do ourselves in the Main method. This $eyword means that you don!t need to instantiate the class in order to use the method. ,ou should only use the static $eyword in specific circumstances, which are beyond the scope of this introductory guide. ' Closer Loo4 at <reeting /ow we $now how a Greeting is used, let!s ta$e a step by step loo$ through the Greeting class. class Greeting { private string 9recipient; The above line declares a variable called Hrecipient. /ote that the variable declaration exists outside of any method. This means that the variable belongs to the class as a whole, rather than to any one method. + variable declared at class level is called a mem2er 7aria2le. The $eyword private refers to the 7isi2ilit- of the member variable. By declaring the variable as private, this prevents any external code from viewing or changing the variable " effectively, the variable is hidden from any code that isn!t part of the Greeting class. t is good practice to declare all member variables as private " in fact, you should hide any of the 2inner wor$ings! of your classes by ma$ing them private. This helps each class to be a 2blac$ box.! ,ou will see the advantage of this later on. n case you were wondering, the underscore character 2H! at the start of the variable name has no special significance in %&. t is merely a naming convention, used to indicate that Hrecipient is a member variable. pu-lic Greeting(" { 9recipient . &Stranger&; # The Greeting method is a special case. + method that has the same name as the containing class is called a constructor, and it is used to create an instance, as the name implies, when the ne) $eyword has been used. Wust now you saw how we declared the Hrecipient member variable as private to hide it from any code outside of the Greeting class. n contrast with the variable, we have declared the constructor as pu-lic, which means that code outside of the Greeting class can call it. %onstructors are usually public, otherwise it would not be possible for outside code to create an instance of the class# /ote that a constructor, unli$e any other method, does not specify a return value or void. The return value is implicit " in this case, the new Greeting instance. n the Greeting constructor, the only action is to initiali4e the Hrecipient member variable to a default value. n this case, the default value is &Stranger&. pu-lic void :isplay(" { string message . &'ello( & 2 9recipient; Console.$rite%ine(message"; # The :isplay method is an ordinary method li$e those we have seen before, except that it is not static. t creates a message based on the recipient!s name and writes the message to the console. pu-lic string 5ecipient { get { return 9recipient; # set { 9recipient . value; # # The last section defines the 5ecipient property. + property is a member of a class that provides access to data in that class in a controlled manner. n this case, the 5ecipient property provides access to the Hrecipient member variable without the need to ma$e Hrecipient public. 'hat!s the deal here( 'hy not Aust ma$e the member variable Hrecipient public, and do away with the 5ecipient property( To understand the answer, you first need to understand how properties wor$. + property has a type, Aust li$e a variable " in the case of the 5ecipient property, its type is string. + property also has get and set accessors, which are li$e methods but without the parameters and are represented in %& by the $eywords get and set. These accessors provide access to the property itself. Gemember this statement in Program.Main5 t,eGreeting.5ecipient . &+ric&; This statement sets the 5ecipient property to have the value OEricO. Behind the scenes, this calls the set accessor in the Greeting class. The set accessor loo$s li$e this5 set { 9recipient . value; # nside the set accessor, there is a pre-defined variable named value that holds the value being assigned to the property. n this case, that value is stored in the Hrecipient member variable. The get accessor wor$s in the opposite way. f the Program.Main method included a line such as this5 Console.$rite%ine(t,eGreeting.5ecipient"; then the program would write OEricO on the console. The get accessor returns the value of the Hrecipient member variable. 0et!s go bac$ to the earlier -uestion " why go to all the trouble of defining a property that has the same effect as ma$ing Hrecipient public( The answer is that, by using the code inside the get and set accessors, you can control access to the Hrecipient member variable. 'hy would you want this control( magine that, at some future point, you want to prevent the 5ecipient property from having a certain value 1such as an empty string3. By adding some code to the set accessor, you can prevent the caller from assigning this value to Hrecipient. 'ithout the property accessor methods, you would have to chec$ every single time any code, anywhere in your program, wrote a value to the Hrecipient member variable. The use of properties to control access to class data is an example of a concept called encapsulation. f you remember bac$ to the explanation of what classes are for, you learned that they add structure to a program by bringing together all the code that relates to a certain part of the program. +s an example of this, by encapsulating the Hrecipient member variable inside a property, you have brought all the code that controls the value of Hrecipient into a single location, instead of the code being scattered all around your program. +s your programs get bigger, you will find them much easier to manage when you can design them so that related code is organi4ed in one place. &ummar- This guide ends Aust as you have met the fascinating subAect of program design, by building your first class. +long the way, you have learned about methods, data types, variables, and controlling program flow with conditionals and loops. These are the basic building bloc$s of any program. >nce you have mastered these tools, you are well on your way to becoming a fully-fledged programmer. f you have enAoyed learning how to ma$e a program wor$, there are many opportunities for you to ta$e your next steps. This guide has only introduced some of the more common building bloc$s, and there are several more for you to discover. /ow that you have learned the basics of the %& programming language, here are some other concepts to learn about on your own5 5sing other loops and conditionals. ,ou have seen the most commonly-used loops and conditionals in this guide. ,ou can also learn about do;),ile loops, 3oreac, loops, and s)itc, statements. Exploring the =*E6 "rame+or4. ,our first program used only the Console framewor$ class. There are hundreds of classes in the ./ET framewor$ that enable you to do anything from networ$ing with other computers to creating ?-dimensional games. 5sing arra-s and collections. +rrays and collections enable you to wor$ with groups of obAects rather than defining an individual variable for each one. $andling exceptions. + program causes an exception when it does something that it shouldn!t, li$e dividing by 4ero. Vood programs are prepared for the unexpected, and can receive notifications of these exceptions so they can ta$e appropriate action. Inheritance> inter)aces and pol-morphism. 'hen you create a class, you can inherit the behavior of an existing class so that your own class behaves in a similar way. ,ou can also use interfaces to define what methods and properties a class should have, so that several different classes can have the same appearance. 5sing <enerics. Venerics enable you to write 2generic! classes, such as collection classes, that can ensure that you don!t put the wrong type of obAect into a collection. The MS./ 'eb site has many more lessons for you to study as you progress to more advanced techni-ues and more complex programs. ;appy learning#
Learn C# From Scratch in One Hour C# Book for Absolute Beginners with Hands On exercises and Real-World Examples the one book you need to quickly Master C# Programming, No prior experience is required