2 C# .NET Variables

Embed Size (px)

Citation preview

  • 8/13/2019 2 C# .NET Variables

    1/61

    Variables in C#

    Programmes work by manipulating data stored in memory. These storage areascome under the general heading of Variables. In this section, you'll see how toset up and use variables. You'll see how to set up both text and numbervariables. y the end of this section, you'll have written a simple calculatorprogramme. !e'll start with something called a Stringvariable.

    String Variables in C#.NET

    The first type of variable we'll take a look at is called a String. "tring variablesare always text. !e'll write a little programme that takes text from a text box,store the text in a variable, and then display the text in a message box.

    ut bear in mind that a variable is #ust a storage area for holding things that you'llneed later. Think of them like boxes in a room. The boxes are empty until you putsomething in them. You can also place a sticker on the box, so that you'll knowwhat's in it. $et's look at a programming example.

    If you've got your pro#ect open from the previous section, click Filefrom themenu bar at the top of %isual &. (rom the (ile menu, click Close Solution."tart a new pro#ect by clicking Fileagain, then New Project. (rom the )ewPro#ect dialogue box, click on !indows *pplication. (or the )ame, type StringVariables.

    &lick +, and you'll see a new form appear. *dd a button to the form, #ust likeyou did in the previous section. &lick on the button to select it -it will have thewhite suares around it/, and then look for the Properties !indow in the bottomright of %isual "tudio. "et the following Properties for your new button0

    Name0 btn"tringsLocation0 12, 345Size0 362, 72Text0 8et Text ox 9ata

    Your form should then look like this0

    1

  • 8/13/2019 2 C# .NET Variables

    2/61

    !e can add two more controls to the form, a $abel and a Text ox. !hen thebutton is clicked, we'll get the text from the text box and display whatever wasentered in a message box.

    * $abel is #ust that0 a means of letting your users know what something is, orwhat it is for. To add a $abel to the form, move your mouse over to the Toolboxon the left. &lick the Labelitem under Common Controls0

    )ow click once on your form. * new label will be added0

    2

  • 8/13/2019 2 C# .NET Variables

    3/61

  • 8/13/2019 2 C# .NET Variables

    4/61

    =ove your mouse back over to the Toolbox. &lick on the TextBoxentry. Thenclick on your form. * new Text ox will be added, as in the following image0

    Instead of setting a location for your text box, simply click it with your left mousebutton. >old your left mouse button down, and the drag it #ust to the right of the$abel.

    )otice that when you drag your text box around, lines appear on the form. Theseare so that you can align your text box with other controls on the form. In theimage below, we've aligned the text box with the left edge of the button and the

    top of the $abel.

    4

  • 8/13/2019 2 C# .NET Variables

    5/61

    +, time to add some code. efore you do, click File > Save llfrom the menubar at the top of %isual &. You can also run your programme to see what itlooks like. Type some text in your text box, #ust to see if it works. )othing willhappen when you click your button, because we haven't written any code yet.$et's do that now. &lick the red ? on your form to halt the programme, and you'll

    be returned to %isual &.

    ssigning Text to a String Variable

    @@ &ontinues from previous lesson

    9ouble click your button to open up the coding window. Your cursor will beflashing inside of the curly brackets for the button code0

    )otice all the minus symbols on the left hand side. You can click these, and it willhide code for you. &lick the minus symbol next to !ublic Form" $. It will turn intoa plus symbol, and the code for #ust this =ethod will be hidden0

    5

    http://www.homeandlearn.co.uk/csharp/csharp_s2p1.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p1.html
  • 8/13/2019 2 C# .NET Variables

    6/61

    >iding code like this makes the rest of the coding window easier to read. ack tothe button code, though. !e're going to set up a string variable. To do this, youneed two things0 the Type of variable you want, and a name for your variable.

    &lick inside the two curly brackets of the button code, and add the following0

    string%irstNameA

    *fter the semi:colon, press the enter key on your keyboard to start a new line.Your coding window will then look like this0

    !hat you have done is to set up a variable called %irstName. The Type ofvariable is a string. )ote that the coding editor will turn the word BstringB blue.lue denotes the variable type : a string, in this case. -+ther variable types areint, %loat, and &ouble. These are all number variables that you'll meet shortly./

    6

  • 8/13/2019 2 C# .NET Variables

    7/61

    *fter you have told & which type of variable you want, you then need to comeup with a name for your variable. This is like the sticker on an empty box. Theempty box is the variable type. Think of these empty boxes as being of differentsi

  • 8/13/2019 2 C# .NET Variables

    8/61

    *fter setting up your variable -telling & to set aside some memory for you/, andgiving it a name, the next thing to do is to store something in the variable. *ddthe following line to your code -don't forget the semi:colon on the end/0

    %irstName , textbox"-Text.

    Your coding window will then look like this0

    To store something in a variable, the name of your variable goes on the left handside of an e/uals sign. *fter an euals sign, you type what it is you want to storein the variable. (or us, this is the Textfrom textbox".

    Fxcept, there's a slight problem. Try to run your code. You should see an errormessage like this one0

    &lick No, and have a look at your code0

    8

  • 8/13/2019 2 C# .NET Variables

    9/61

    There is a blue wiggly line under textbox3. >old your mouse over this and %isual"tudio will tell you that0

    T'e name 0textbox"0 &oes not exist in t'e current context-

    If you see an error like this, which is uite common, it means that %isual &cannot find anything with the name you've #ust typed. "o it thinks we don't have atextbox called textbox3. *nd we don't; It's called textox3. !e've typed alowercase BbB when it should be an uppercase BB. "o it's important to rememberthat & is case sensitive. This variable name0

    %irstName

    Is different to this variable name0

    FirstName

    The first one starts with a lowercase BfB and the second one starts with anuppercase B(B.

    9elete the lowercase BbB from your code and type an uppercase BB instead. Gunyour programme again and you won't see the error message. )ow stop yourprogramme and return to the coding window. The blue wiggly line will havedisappeared.

    !hat have so far, then, is the following0

    string%irstName.%irstName , textBox"-Text.

    The first line sets up the variable, and tells & to set aside some memory that willhold a stringof text. The name of this storage area will be %irstName.

    The second line is the one that actually stores something in the variable : theText from a text box called textBox".

    )ow that we have stored the text from the text box, we can do something with it.In our case, this will be to display it in a message box. *dd this line to your code0

    1essageBox-S'ow%irstName$.

    The =essageox."how- / =ethod is one you've #ust used. In between the roundbrackets, you can either type text surrounded by double uotes, or you can typethe name of a string variable. If you're typing the name of a variable, you leavethe double uotes off. You can do this because & knows what is in your variable-you have #ust told it on the second line of your code./

    9

  • 8/13/2019 2 C# .NET Variables

    10/61

    Gun your programme again. Type something in your text box, and then click thebutton. You should see the text you typed0

    >alt your programme and return to the coding window.

    ssigning text to a String Variable

    *s well as assigning text from a text box to your variable, you can assign text like

    this0

    %irstName , 23ome an& Learn2.

    +n the right hand side of the euals sign, we now have some direct textsurrounded by double uotes. This then gets stored into the variable on the lefthand side of the euals sign. To try this out, add the following two lines #ustbelow your =esageox line0

    %irstName , 23ome an& Learn2.1essageBox-S'ow%irstName$.

    Your coding window will then look like this0

    10

  • 8/13/2019 2 C# .NET Variables

    11/61

    Gun your programme again. Type something in the text box, your own first name.Then click the button. You should see two message boxes, one after the other.The first one will display your first name. ut the second will display B>ome and$earnB.

    !e're using the same variable name, here0 %irstName. The first time we used it,we got the text directly from the text box. !e then displayed it in the =essage

    ox. !ith the two new lines, we're typing some text directly in the code, B>omeand $earnB, and then assigning that text to the %irstNamevariable. !e've thenadded a second =essageox."how- / method to display whatever is in thevariable.

    In the next part of this lesson, you'll learn about something called &oncatenation.

    Concatenation in C#

    @@ &ontinues from previous lesson

    *nother thing we can do is something called &oncatenation. &oncatenation is#oining things together. You can #oin direct text with variables, or #oin two or morevariables to make a longer string. * coding example may clear things up.

    9elete the two new lines you've #ust added. )ow add a second variable, #ustbelow the first one0

    stringmessageText.

    "o you coding window should look like this0

    11

    http://www.homeandlearn.co.uk/csharp/csharp_s2p2.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p2.html
  • 8/13/2019 2 C# .NET Variables

    12/61

    !e want to store some text inside of this new variable, so add the following lineof code #ust below string messageText0

    messageText , 24our name is5 2.

    Your code window will then look like ours below0

    !hen the message box displays, we want it say some thing like BYou name isHohnB. The variable we've called messageTextholds the first part of the string,BYour name is B. *nd we're getting the persons name from the text box0

    %irstName , textBox"-Text.

    The person's name is being stored in the variable called %irstName. To #oin thetwo together -concatenate/ & uses the plus symbol - /.

    messageText 6 %irstName

    Instead of #ust %irstNamebetween the round brackets of =essageox."how- /,we can add the messageTextvariable and the plus symbol0

    =essageox."how-messageText 6 %irstName/A

    *mend your =essageox line so it's the same as the one above. >ere's thecoding window0

    12

  • 8/13/2019 2 C# .NET Variables

    13/61

    Gun your programme. Type your first name into the text box, and then click yourbutton. You should see something like this0

    "o we set up a variable to hold some direct text, and got the person's name fromthe text box. !e stored this information in two different variables. To #oin the twotogether, we used the plus symbol. !e then displayed the result in a messagebox.

    ut you can also do this0

    1essageBox-S'ow 24our name is5 2 6 %irstName$.

    >ere, we're not storing the text in a variable called messageText. Instead, it's#ust direct text surrounded by double uotes. )otice, though, that we still use theplus symbol to #oin the two together.

    Comments in C# -N7T

    @@ &ontinues from previous lesson

    You don't have to use a message box to display the result. You can use othercontrols, like a $abel. $et's try it.

    *dd a new $abel to your form. Jse the Properties !indow to set the followingproperties for your new $abel0

    13

    http://www.homeandlearn.co.uk/csharp/csharp_s2p3.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p3.html
  • 8/13/2019 2 C# .NET Variables

    14/61

    Name0 Text=essageLocation0 D4, 36KText0 =essage *rea

    Geturn to your coding window, and add two forward slashes to the start of your

    =essageox."how- / line. The line should turn green, as in the following image0

    The reason it turns green is that two forward slashes are the characters you useto add a comment. & then ignores theses lines when running the programme.&omments are a very useful way to remind yourself what the programme does,or what a particular part of your code is for. >ere's our coding window with somecomments added0

    You can also use the menu bar, or the toolbar, to add comments. >ighlight anyline of text in your code. (rom the menu bar at the top of %isual &, select 7&it >&vance& > Comment Selection. Two forward slashes will be added to the

    14

  • 8/13/2019 2 C# .NET Variables

    15/61

    start of the line. You can uickly add or remove comments by using the toolbar.$ocate the following icons on the toolbars at the top of %isual &0

    In version 6236, the comment icons look like this0

    The comment icons are circled in red, in the images above. The first one adds acomment, and the second one removes a comment. -If you can't see the aboveicons anywhere on your toolbars, click View > Toolbars > Text 7&itor./

    )ow that you have commented out the =essageox line, it won't get executedwhen your code runs. Instead, add the following like to the end of your code0

    Text1essage-Text , messageText 6 %irstName.

    Your coding window should then look like this0

    Gun your programme again. Type your name in the text box, and then click yourbutton. The message should now appear on your label, instead of in a =essageox0

    15

  • 8/13/2019 2 C# .NET Variables

    16/61

    The reason is does so is because you're now setting the Text property of the$abel with code. Previously, you changed the $abel's Text Property from theProperties !indow. The name of our label is Text1essage. To the right of theeuals sign, we have the same code that was in between the round brackets ofthe "how- / method of the =essageox.

    +, time for an exercise.

    7xercise*dd a second text box to your form. 9isplay your message in the text box as wellas on the label. "o if your name is Hohn, your second text box should have0 BYourname is0 HohnB in it after the button is clicked.

    !hen you complete this exercise, your form should look like this, when thebutton is clicked0

    16

  • 8/13/2019 2 C# .NET Variables

    17/61

    !eLre now going to move away from string variables and on to number variables.The same principles youLve #ust learnt still apply, though0

    "et up a variable, and give it a name

    "tore something in the variable

    Jse code to manipulate what you have stored

    Numbers Variables in C# -N7T

    *s well as storing text in memory you can, of course, store numbers. There are anumber of ways to store numbers, and the ones you'll learn about now are calledInteger, 9ouble and (loat. (irst up, though, are Integer variables.

    (irst, close any solution you have open by clicking File > Close Solutionfromthe menu bar at the top of %isual "tudio. "tart a new pro#ect by clicking File >New Project. (rom the )ew Pro#ect dialogue box, select 8in&ows Forms!!licationfrom the available templates. Type a )ame for your pro#ect. &all itNumbers.

    &lick +, and you'll have a new form to work with.

    C# 9ntegers

    17

  • 8/13/2019 2 C# .NET Variables

    18/61

    *n integer is a whole number. It's the K of K.5, for example. In programming,you'll work with integers a lot. ut they are #ust variables that you store inmemory and want to manipulate. You'll now see how to set up and use Integervariables.

    *dd a button to your form, and set the following properties for it in the Properties!indow0

    Name0 btnIntegersText0 IntegersLocation0 332, 62

    )ow double click your button to get at the code0

    In the previous section, you saw that to set up a string variable you #ust did this0

    stringmyTextA

    You set up an integer variable in the same way. Fxcept, instead of typing theword string, you type the word int-short for integer/.

    "o, in between the curly brackets of your button code, type int. You should seethe word turn blue, and the Intelli"ense list appear0

    18

  • 8/13/2019 2 C# .NET Variables

    19/61

    Fither press the enter key on your keyboard, or #ust hit the spacebar. Then type aname for your new variable. &all it m(9nteger. *dd the semi:colon at the end ofyour line of code, and hit the enter key. Your coding window will then look like

    this0

    )otice the text in the yellow box, in the image one up from the one above. Itsays0

    :e!resents a ;*

  • 8/13/2019 2 C# .NET Variables

    20/61

    "o we've set up an integer variable called myInteger. +n the second line, we'restoring a value of 65 inside of the variable.

    !e'll use a message box to display the result when the button is clicked. "o addthis line of code for line three0

    =essageox."how-m(9nteger/A

    )ow try to run your code. You'll get the following error message0

    You should see a blue wiggly line under your =essageox code0

    >old your mouse over m(9nteger, between the round brackets of S'ow- /. Youshould see the following yellow box0

    20

  • 8/13/2019 2 C# .NET Variables

    21/61

    The error is0 B&annot convert from int to stringB. The reason you get this error isbecause m(9ntegerholds a number. ut the =essageox only displays text. &does not convert the number to text for you. It doesn't do this because & is aprogramming language known as Bstrongly typedB. !hat this means is that youhave to declare the type of variable you are using -string, integer, double/. & will

    then check to make sure that there are no numbers trying to pass themselves offas strings, or any text trying to pass itself off as a number. In our code above,we're trying to pass m(9ntegeroff as a string. *nd & has spotted it;

    !hat you have to do is to convert one type of variable to another. You canconvert a number into a string uite easily. Type a full stop -period/ after the BrB ofmyInteger. You'll see the Intelli"ense list appear0

    "elect ToStringfrom the list. ecause ToStringis a method, you need to type apair of round brackets after the BgB of To"tring. Your code will then look like this

    -we've highlighted the new addition/0

    The To"tring method, as its name suggests, converts something to a string oftext. The thing we are converting is an integer.

    "tart your programme again. ecause you've converted an integer to a string,you should find that it runs + now. &lick your button and you should see themessage box appear0

    21

  • 8/13/2019 2 C# .NET Variables

    22/61

    In the next lesson, we'll take a look at double variables, and float variables.

    ouble an& Float Variables in C#

    Integers, as was mentioned, are whole numbers. They can't store the pointsomething, like .4, .M6, and .224. If you need to store numbers that are not wholenumbers, you need a different type of variable. You can use the &oubletype, orthe %loattype. You set these types of variables up in exactly the same way0instead of using the word int, you type double, or float. $ike this0

    floatmy(loatAdoublemy9oubleA

    -(loat is short for Bfloating pointB, and #ust means a number with a pointsomething on the end./

    The difference between the two is in the si

  • 8/13/2019 2 C# .NET Variables

    23/61

    To get some practice using floats and doubles, return to your form. If you can'tsee the Form"-cs ?esign@tab at the top, right click (orm3.cs in the "olutionFxplorer on the right hand side. -If you can't see the "olution Fxplorer, click %iew "olution Fxplorer from the menu bar at the top./

    *dd a new button to your form. "et the following properties for it in the Properties!indow0

    Namebtn(loatLocation0 332, 45Text0 (loat

    9ouble click your new button, and add the following line to the button code0

    floatmy(loatA

    Your coding window will then look like this0

    23

  • 8/13/2019 2 C# .NET Variables

    24/61

    To store something inside of your new variable, add the following line0

    m(Float , A-*F.

    The capital letter ( on the end means (loat. You can leave it off, but & thentreats it like a double. ecause you've set the variable up as a float, you'll geterrors if you try to assign a double to a float variable.

    *dd a third line of code to display your floating point number in a message box0

    =essageox."how-m(Float-ToString $/A

    *gain, we have to use To"tring- / in order to convert the number to a string oftext, so that the message box can display it.

    ut your coding window should look like ours below0

    Gun your programme and click your (loat button. You should see a form like this0

    24

  • 8/13/2019 2 C# .NET Variables

    25/61

  • 8/13/2019 2 C# .NET Variables

    26/61

    )ow run your programme again. !hen you click the button, your message boxwill be this0

    It's missed the 4 out; The reason for this is that float variables can only hold 4numbers in total. If there's more than this, & will round up or down. * numberthat ends in 5 or more will be rounded up. * number ends in 5 or less will berounded down0

    "*;-=DE-eight numbers ending in D : round up/"*;-=D-eight numbers ending in M : round down/

    The number of digits that a variable can hold is known as !recision. (or floatvariable, & is precise to 4 digits0 anything more and the number is rounded off.

    In the next part, we'll take a closer look at doubles

    ouble Variables in C# -N7T

    @@ &ontinues from the previous lesson

    *dd another button to your form, and set the following properties for it in theProperties !indow0

    Name0 btn9oubleLocation0 332, 372Text0 9ouble

    9ouble click your new button to get at the code. *dd the following three lines toyour button code0

    doublemy9oubleA

    my9ouble N 2.224A

    =essageox."how-my9ouble.To"tring-//A

    Your coding window should now look like this0

    26

    http://www.homeandlearn.co.uk/csharp/csharp_s2p6.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p6.html
  • 8/13/2019 2 C# .NET Variables

    27/61

    Gun your programme and click your new button. You should see this0

    You also need to be careful of precision when using double variable types. Thedouble type can hold up to 3K digits.

    >alt your programme and return to the coding window. &hange this line0

    m(ouble , A-AAD.

    to this0

    m(ouble , "*;=DE-"*;=D.

    Gun your programme and click your double button. The message box correctlydisplays the number. *dd another number on the end, though, and & will againround up or down. The moral is, if you want accuracy, careful of rounding;

    In the next part, you'll see how to add up in &.

    &&ition in C# -N7T

    27

  • 8/13/2019 2 C# .NET Variables

    28/61

    !e'll now use variables to do some adding up. *fter you have learned how toadd up with the three number variable types, we can move on to subtraction,multiplication, and division.

    "tart a new pro#ect for this. "o click File > Close Solutionfrom the menu bar atthe top of %isual &. Then click File > New Project. Type arit'meticas the)ame of your new !indows (orms *pplication pro#ect.&lick + to create thenew pro#ect.

    *dd a button to your new form, and set the following properties for it in theProperties !indow0

    Name0 btn*ddSize0 322, 72Text0 Integer : *dd

    =ove the button to the top of your form. Then double click it to get at the codingwindow. "et up the following three integer variables in your button code0

    intfirst)umberAintsecond)umberAintinteger*nswerA

    Your coding window should look like ours below0

    !e now need to put something into these variables. !e'll store 32 in the firstnumber, and 76 in the second number. "o add these two lines to your code0

    %irstNumber , "A.

    secon&Number , ;*.

    Your coding window will then look like this0

    28

  • 8/13/2019 2 C# .NET Variables

    29/61

    "o the numbers we want to store in the variables go on the right hand side of theeuals signA the variable names go on the left hand side of the euals sign. Thisassigns the numbers to the variables : puts them into storage.

    !e now want to add the first number to the second number. The result will bestored in the variable we've called integernswer. (ortunately, & uses the plussymbol -/ to add up. "o it's fairly simple. *dd this line to your code0

    integernswer , %irstNumber 6 secon&Number.

    *nd here's the coding window0

    !e've already stored the number 32 in the variable called %irstNumber. !e'vestored 76 in the variable secon&Number. "o we can use the variable names toadd up. The two variables are separated by the plus symbol. This is enough totell & to add up the values in the two variables. The result of the addition thengets stored to the left of the euals sign, in the variable called integernswer.

    Think of it like this0

    29

  • 8/13/2019 2 C# .NET Variables

    30/61

    Calculate t'is sum %irst

    Store t'e answer 'ere

    To see if all this works or not, add a message box as the final line of code0

    1essageBox-S'ow integer*nswer.To"tring- /$.

    !e're #ust placing the integernswervariable between the round brackets of"how- /. ecause it's a number, we've had to use To"tring- / to convert thenumber to text. >ere's what your coding window should look like now0

    30

  • 8/13/2019 2 C# .NET Variables

    31/61

    *nd here's the form when the button is clicked0

    You don't have to store numbers in variables, if you want to calculate things. Youcan #ust add up the numbers themselves. $ike this0

    integernswer , "A 6 ;*.

    *nd even this0

    integernswer , %irstNumber 6 ;*.

    "o you can add up #ust using numbers, or you can mix variable names withnumbers. *s long as & knows that there's a number in your variable, and thatit's the right type, the addition will work.

    31

  • 8/13/2019 2 C# .NET Variables

    32/61

    You can use more than two variables, or more than two numbers. "o you can dothis0

    integernswer , %irstNumber 6 secon&Number 6 t'ir&Number.

    or this0

    integernswer , %irstNumber 6 secon&Number 6 ;*.

    *nd this0

    integernswer , %irstNumber 6 "A 6 ;*.

    The results is the same0 & adds up whatever you have on the right hand side ofthe euals sign, and then stores the answer on the left hand side.

    In the next part, you'll see how to add up with float variables.

    &&ing u! wit' %loat Variables

    @@ &ontinues from the previous lesson

    You add up with float variables in exactly the same way : with the plus symbol.You can even mix integer variables with float variables. ut you have to takecare;

    *dd another button to your form, and set the following properties for it in theProperties !indow0

    Name0 btn*dd(loatsSize0 322, 72Text0 (loat : *dd

    9ouble click your button to get at the code. "et up the following variables0

    floatfirst)umberAfloatsecond)umberAfloatfloat*nswerA

    *nd here's the coding window0

    32

    http://www.homeandlearn.co.uk/csharp/csharp_s2p8.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p8.html
  • 8/13/2019 2 C# .NET Variables

    33/61

    -)otice that we've used the same names for the first two variables. & doesn'tget confused, because they are in between the curly brackets of the button code.You can set up variables outside of the curly brackets. !e'll do this when wecome to code the calculator, at the end of this section. Then something calledscope comes in to play. 9on't worry about it, for now./

    To place something in your new variables, add the following code0

    %irstNumber , "A-=F.

    secon&Number , ;*-=F.

    %loatnswer , %irstNumber 6 secon&Number.

    (inally, add you message box line0

    1essageBox-S'ow %loatnswer-ToString $ $.

    The coding window should look like this0

    Gun your form and click your new button. You should see this0

    33

  • 8/13/2019 2 C# .NET Variables

    34/61

    "o 32.5 76.5 euals M7. >alt your form by clicking the red ?, and return to yourcoding window.

    *s was mentioned, you can add float and integer values together. ut you needto take care. Try this0

    *dd the following variable to your code0

    intinteger*nswerA

    *nd then change this line0

    %loatnswer , %irstNumber 6 secon&Number.

    To this0

    integernswer , %irstNumber 6 secon&Number.

    "o it's #ust the name of the variable before the euals sign that needs to be

    changed.

    *mend you message box line from this0

    1essageBox-S'ow %loatnswer-ToString $ $.

    To this0

    34

  • 8/13/2019 2 C# .NET Variables

    35/61

    1essageBox-S'ow integernswer-ToString$ $.

    Your coding window will then look like this0

    Try to run your code. The programme won't execute, and you'll have a bluewiggly line0

    >old your mouse over the blue wiggly line and you'll see an explanation of theerror0

    )ot much help, if you're a beginner; ut what it's telling you is that the firstnumber and the second number are float variables. The answer to the additionwas also a float. >owever, you were trying to store the answer in an integervariable. & won't let you store float values in an integer. The error message issaying that you need to convert them first.

    35

  • 8/13/2019 2 C# .NET Variables

    36/61

    You can indeed convert float values to integers. You do it like this0

    integernswer , int$ %irstNumber 6 int$ secon&Number.

    "o you type the word intbetween a pair of round brackets. This goes before the

    number you want to convert. It does mean that the point something on the endwill get chopped off, though. "o 32.5 becomes 32, and 76.5 becomes 76. )otgood for accuracy, but at least the programme will run;

    Try it out, and you should see an answer of M6 when you click your button.

    "o the moral is this0 If you're expecting an answer that ends in point something,use a float variable -or a double/.

    -You may have a green wiggly line under float %loatnswer. This is becauseyou're not storing anything in this variable. 9on't worry about it;/

    )ote that the other way round is not a problem : you can store an integer in afloat value. >ave a look at this slight change to the code0

    (irst, notice the new way we are storing the number 62 into the integer variablecalled integernswer0

    intinteger*nswer N 62A

    Instead of two lines, we've #ust used one. This is fine, in &. ut you're doing twothings on the same line0 setting up the variable, and placing a value in it.

    The second thing to notice is that we are adding up two float values -first)umberand second)umber/ and an integer -integer*nswer/. !e're then storing theanswer into a float variable -float*nswer/. Try it out and you'll find that the coderuns fine.

    36

  • 8/13/2019 2 C# .NET Variables

    37/61

    If we change this line0

    %irstNumber , "A-=F.

    to this0

    %irstNumber , "A.

    then, again, the programme will run fine. In other words, you can store an integerin a float variable, but you can't store a float value in an integer variable withoutconverting.

    >opefully, that wasn't too confusing;

    !e'll move on to subtraction, now. ut if you want to use a double variableinstead of a float variable the same things apply : be careful of what you are

    trying to store, and where;

    Subtraction in C# -N7T

    @@ &ontinues from the previous lesson

    "ubtraction is fairly straightforward in &. To subtract one number from another,you use the minus symbol - : /.

    *dd another button to your form. "et the following properties for it in theProperties !indow0

    Name5 btnSubtractSize5 "AA ;A>Text5 Subtract

    9ouble click the button to get at the code. *dd the following three lines of code0

    intanswerSubtractA

    answerSubtract , =A < *=.

    1essageBox-S'ow answerSubtract-ToString$ $.

    Your coding window will then look like this0

    37

    http://www.homeandlearn.co.uk/csharp/csharp_s2p9.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p9.html
  • 8/13/2019 2 C# .NET Variables

    38/61

    "o we've set up an integer variable called answerSubtract. +n the second line,we're using the minus symbol to subtract 65 from 52. !hen & works out theanswer to 52 : 65, it will place the answer to the left of the euals sign, in theanswerSubtractvariable. +n the final line, we're displaying the answer in amessage box.

    Gun your code, and make sure it works. The answer you should see in the

    message box is, of course, 65. "top your programme and return to the codingwindow. )ow change the 65 to 65.5.

    answerSubtract , =A < *=-=.

    Try to run your programme and you'll get the blue wiggly line, meaning there's anerror in your code. The reason is the same as for addition0 we're trying to place afloat number into an integer variable -the answer will be 6M.5, this time/. Hustbecause the math symbol has changed doesn't mean we can disobey the &rules;

    &hange it back to 65, and the code will run fine.

    *s with addition, you can subtract more than one number. &hange your line tothis0

    answerSubtract , =A < *= < "A < *.

    !hen you run your programme, you should see 37 in your message box, theanswer to the subtraction.

    You can also use variable names in your subtraction. *dd the following integer

    variable to your code0

    intnumber+ne N 36A

    Then change the second line to this0

    answerSubtract , =A < numberGne.

    38

  • 8/13/2019 2 C# .NET Variables

    39/61

  • 8/13/2019 2 C# .NET Variables

    40/61

    Name0 btn=ixedSize0 322, 72Text0 *dd and "ubtract

    -If you need to make your (orm bigger, click on the form to select it. Then

    change the "i

  • 8/13/2019 2 C# .NET Variables

    41/61

    "top the programme and return to your code.

    !e now want to subtract the third number from the first two. "o change this line0

    answer , %irstNumber 6 secon&Number.

    to this0

    answer , %irstNumber 6 secon&Number < t'ir&Number.

    !hen & sees all these variables after the euals sign, it will try to calculateusing the numbers you've stored in the variables. Jsually, it will calculate fromleft to right. "o this bit gets done first0

    %irstNumber 6 secon&Number

    !hen & finishes adding the first two numbers, it will then deduct the value int'ir&Number. The answer is then stored in the variable to the left of the eualssign.

    Gun your programme. !hen the button is clicked, the message box will displayan answer of 365.

    "o mixing addition and subtraction is fairly straightfoward : #ust use the and :symbols. >owever, there can be problems; In the next part, you'll aboutsomething called +perator Precedence.

    G!erator Prece&ence in C# -N7T@@ &ontinues from the previous lesson

    The symbols you have been using - and : / are known as +perators. +peratorPrecedence refers to the order in which things are calculated. & sees the plus-/ and the minus - : / as being of eual weight, so it does the calculating fromleft to right. ut this Bleft to rightB calculating can cause you problems. &hangethe plus into a minus in your code, and the minus into a plus. "o change it to this0

    answer , %irstNumber < secon&Number 6 t'ir&Number.

    Gun your code. !hen the button is clicked, an answer of 45 will appear in themessage box, instead of the 365 you got last time; This is Bleft to rightBcalculation. !hat you wanted here was0

    %irstNumber < secon&Number

    41

    http://www.homeandlearn.co.uk/csharp/csharp_s2p11.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p11.html
  • 8/13/2019 2 C# .NET Variables

    42/61

    Then when the answer to that is found, add the t'ir&Number. "o the sum is this0322 : 45, which euals 65. Then 65 52, which euals 45.

    ut what if you didn't mean thatC !hat if you wanted %irstNumberminus theanswer to secon&Number 6 t'ir&NumberC In case that's not clear, some

    brackets may help clear things up. >ere's the two ways of looking at ourcalculation0

    %irstNumber < secon&Number $ 6 t'ir&Number

    %irstNumber < secon&Number 6 t'ir&Number $

    In maths, brackets are a way to clear up your calculations. In the first one,whatever is between the round brackets is calculated first. The total of the sum inbrackets is then added to t'ir&Number. In the second one, it's the other wayaround0 second)umber is first added to third)umber. You then deduct from this

    total the value of first)umber.

    You can use brackets in programming, as well. *dd the following brackets toyour code0

    answer , %irstNumber < secon&Number 6 t'ir&Number$.

    Your coding window should then look like this0

    !hen you run your programme and click the button, this time the answer isminus 65. Previously, the answer was 45; The reason the answer is different isbecause you've used brackets. & sees the brackets and tackles this problemfirst. The next thing it does is to deduct %irstNumberfrom the total. !ithout thebrackets, it simply calculates from left to right.

    42

  • 8/13/2019 2 C# .NET Variables

    43/61

    1ulti!lication an& ivision in C#

    @@ &ontinues from the previous lesson

    To multiply and divide, the following symbols are used in & programming0

    H=ultiplyI9ivide

    &hange your code to this0

    answer , %irstNumber 6 secon&Number $ Ht'ir&Number.

    ecause of the brackets, the first thing that & does is to add the value in%irstNumberto the value in secon&Number. The total is then multiplied - Q / by

    the value in t'ir&Number. !ith the values we currently have in the variables, thesum is this0

    answer , "AA 6 D= $ H =A

    Gun your programme and click your button. The answer you should get is D452.Geturn to the coding window. )ow remove the two round brackets. Your codingwindow will then be this0

    Gun your programme again. &lick the button. This time, the answer is 7D52; Thereason it's different is because of +perator Precedence. !ith the brackets, youforced & to calculate the addition first. !ithout the brackets, & no longercalculates from left to right. "o it's )+T doing this0

    "AA 6 D= $ H =A

    43

    http://www.homeandlearn.co.uk/csharp/csharp_s2p12.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p12.html
  • 8/13/2019 2 C# .NET Variables

    44/61

    & sees multiplication as having priority over addition and subtraction. "o it doesthe multiplying first. It does this0

    "AA 6 D= H =A $

    The two give you totally different answers.

    The same is true of division. Try this. *mend your line of code to the following0

    answer , %irstNumber 6 secon&Number $I t'ir&Number.

    Gun the programme and the answer will be 7. -The real answer to -322 45/ R 52is, of course, 7.5. ut because we're using integer variables and not floats, thepoint something at the end gets chopped off./

    "o we're using the divide symbol now - R /, instead of the multiplication symbol

    -Q/. The addition is done first, because we have a pair of round brackets. Thetotal of the addition is then divided by the value in third)umber.

    Geturn to the code, and change the line to this0

    answer , %irstNumber 6 secon&Number I t'ir&Number.

    "o #ust remove the round brackets. Gun your programme again, and you'll findthat the answer in the message box is now 323. -It would have been 323.5, if wehad used a float variables instead of integers./

    If you now replace the plus symbol - / above with a multiplication symbol - Q /,& switches back to Bleft to rightB calculation. This is because it sees division andmultiplication as having eual weight. The answer you'll get without brackets is352.

    7xercise BTry the following two lines. (irst this one

    answer , %irstNumber Hsecon&Number$ I t'ir&Number.

    *nd now this one0

    answer , %irstNumber Hsecon&Number I t'ir&Number$.

    !hat answer do you get with the round brackets in different placesC &an youunderstand whyC If not, go back over this section.

    Jetting Numbers %rom Text Boxes

    44

  • 8/13/2019 2 C# .NET Variables

    45/61

  • 8/13/2019 2 C# .NET Variables

    46/61

    "o double click your button to get at the coding window. Your cursor will beflashing inside of the button code. "et up two integer variables at the top of thebutton code0

    int %irstTextBoxNumber.

    int answer.

    Your coding window should look like this0

    To get at the number in the text box, we can use the Textproperty of text boxes.>ere's the line of code to add0

    %irstTextBoxNumber , tbFirstNumber-Text.

    This says, find a text box called tbFirstNumber. *ccess its Textproperty. !henthe Text property is retrieved, store it in the variable called %irstTextBoxNumber.

    To display the number in a message box, add this line0

    1essageBox-S'ow %irstTextBoxNumber-ToString $ $.

    Try to Gun your code. You should find & won't run it at all. It will give you thefollowing error0

    !ith text boxes, the thing that you get is, not surprisingly, text. >owever, we'retrying to store the text from the text box into an integer variable. & won't let youdo this : whole numbers belong in integer variables, not text. The error message

    46

  • 8/13/2019 2 C# .NET Variables

    47/61

  • 8/13/2019 2 C# .NET Variables

    48/61

    (or now, let's move on.

    +, so we've got text from a text box and displayed it in a message box. !hatwe'll do now is to add a second text box, get numbers from both, use our =athoperators, and do some calculations with the two number we took from the text

    boxes. "ounds complex, but it isn't;

    *dd a second text box to your form. "et the following Properties for it in theProperties !indow0

    Name0 tb"econd)umberSize0 52, 62Location0 3K5, 75Text0 5

    Your form will then look like this0

    9ouble click the button to get at your code. )ow set up another integer variableto hold the second number from the new text box0

    int secon&TextBoxNumber.

    To store the number from the text box in this new variable, add the following line0

    secon&TextBoxNumber , int-Parse tbSecon&Number-Text $.

    This is the same as before : use int-Parseto convert the number from the textbox into an integer variable. Then store the number in the new variable.

    48

  • 8/13/2019 2 C# .NET Variables

    49/61

    $et's add the two numbers up, first. !e can use the answer variable for this.>ere's the code to add0

    answer , %irstTextBoxNumber 6 secon&TextBoxNumber.

    "o we're #ust using the plus symbol - / to add up whatever is in the twovariables. The numbers in the variables come from the two text boxes.

    *mend your message box line to this0

    1essageBox-S'ow answer.To"tring- /$.

    *ll you need to do is to change the name of the variable that your are convertingTo"tring- /.

    Your coding window should look like ours0

    Gun your programme, and then click the button. You should the answer to theaddition in your message box0

    49

  • 8/13/2019 2 C# .NET Variables

    50/61

    &hange the numbers in the text boxes, and click your button again. !hen you'vefinished playing with your new form, click the red ? to return to the code. >ereare a few exercises for you to try.

    7xerciseJse the textboxes on your form to calculate the following -you'll need to amendyour code for three of them/0

    3DM5 6D5D7M52 : 6D5

    75 Q D55K5K R 4

    -The answers you should get are0 M427, 73K5, 6145 and D2D./

    7xercise*dd a new text box to you form. "et up an integer variable to store a third

    number. 8et the third number from the text box and calculate the following0

    -3DM5 6D5D/ : 75K-7M52 : 6D5/ Q 36

    75 Q - D5 : D /-5K5K R 4/ 635K

    50

  • 8/13/2019 2 C# .NET Variables

    51/61

    -The answers you should get are0 M7M4, 741D2, 6K15 and 61KM. You'll have tokeep closing the form down. Then add round brackets, the operator symbols, andthe new variable./

    +nce you've completed the exercises, you can move on to tackling the nextpro#ect : your very own calculator;

    C# -N7T Calculator < esign Stage

    You're now going to write your own very own & .)FT calculator programme.!e'll keep it simple at first, and the only thing it will be able to do is add up. *fteryou understand how it all works, we'll make it divide, subtract and multiply.%ersion 3 of your calculator will look like this0

    *s you can see, it has a text box for the display of numbers, buttons for thenumbers 2 to 1, a point symbol, plus and euals buttons, and a clear button.

    51

  • 8/13/2019 2 C# .NET Variables

    52/61

    "o the first thing to do is to design your calculator. "tart a new pro#ect by clicking(ile )ew pro#ect. (or your new form, set the following properties0

    Size0 MM2, MD4Text0 &alculator

    To add a bit of colour to your calculator, you can change the ack&olour propertyof the form, as in the image below0

    !e went for an orange colour, but feel free to choose any colour you like.

    )ow add a text box to your form and set the following properties for it0

    Name0 txt9isplayLocation0 KK, 56Size0 622, 6KTextlign0 Gight

    Time to add the buttons. You need 32 buttons for the numbers 2 to 1. *dd thefirst button to the form, and set the following properties for it0

    Name0 btnSeroFont0 =icrosoft "ans "erif, old, 36

    52

  • 8/13/2019 2 C# .NET Variables

    53/61

    Location0 3M7, 74DSize0 M1, M2Text0 2

    This is the ave a look at the properties window, though,and you'll see that the new button has the )ame button3. &hange it to btnTwo.Then change the Text property to *. 9rag it in to position next to your number 3button.

    *dd the other number buttons in the same0 &opy, Paste, change the Nameandthe Textproperties. (or the other number buttons, use the following for the)ame properties0 btnThree, btn(our, btn(ive, etc. Position your buttons like ours.

    *dd a new button for the Point symbol. 8ive it the )ame btnPoint, and type afull stop -period/ for the Text property. &hange the (ont property, if you think it's

    too small.

    +nly three buttons to go. "o add three more buttons, and use the followingproperties0

    Name0 btnPlusFont0 =icrosoft "ans "erif, old, 36Location0 76M, 351Size0 M1, M2Text0

    Name0 btnFualsFont0 =icrosoft "ans "erif, old, 36Location0 76M, 672Size0 M1, M2Text0 N

    Name0 btn&learFont0 =icrosoft "ans "erif, old, D

    53

  • 8/13/2019 2 C# .NET Variables

    54/61

    Location0 76M, 725Size0 M1, M2Text0 &lear

    &hange the locations, though, if they don't match the alignment for your own

    buttons. ut you've now completed the design of your calculator. "ave your hardwork, and we can begin the coding in the next part.

    C# -N7T Calculator < T'e Co&e

    @@ &ontinues from the previous section

    efore we get to the code, let's #ust go through how our calculator is going towork0

    3. &lick the number buttons. This will be the first number in the addition6. The first number you want to add will then appear in the text box7. &lick the Plus button to tell the calculator you want to addM. The first number will disappear from the text box, ready for the second

    number5. &lick the number buttons again to add the second numberK. &lick the euals button and the answer appears in the text box

    The first task on the list is to get the number to appear in the text box when anumber button is clicked. To do this, double click your number 3 button to get atthe code.

    The numbers on the buttons were put there by changing the Text property. "othe only thing we need to do is to access this Text property. !e can then use thebutton text as the text Property for the text box. *dd the following line for yourbtnGnecode0

    txt9isplay.TextN btn+ne.TextA

    This says, B=ake the Text in the text box the same as the Text that's on thebuttonB. Gemember0 whatever is on the right of the euals sign gets stored inwhatever is on the left of the euals sign.

    Gun your programme and try it out. &lick the number 3 button and it will appearin your text box. &lick your number 3 a few times and what do you noticeC Youmight think that clicking the number 3 button twice, for example, will cause thetext box to display 33, and not 3. *fter all, you clicked it twice, so why shouldn'ttwo number 3's appearC

    The reason is doesn't is because you haven't told & to keep the value that wasalready there. Fach time you click the button, & is starting afresh : it doesn't

    54

    http://www.homeandlearn.co.uk/csharp/csharp_s2p15.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p15.html
  • 8/13/2019 2 C# .NET Variables

    55/61

    know what was in there before, and discards the number that you previouslystored.

    >alt your programme and return to your code. &hange your line to this0

    txtis!la(-Text , txtis!la(-Text 6 btnGne-Text.

    This line is easier to read if you #ust look at the part after the euals sign. !hichis this0

    txtis!la(-Text 6 btnGne-Text.

    !hen you're working with text, the plus symbol doesn't mean add : it meansconcatenate -you learned about this in the previous section when workingstrings/. "o & will #oin the text in the text box with the text on the button. *fter ithas finished doing this, it will store the answer to whatever is on the left of the

    euals sign. In this case, it's not a variable but the text property of the text box.

    Gun your programme again. &lick the number one button a few times. Youshould find that the number one will appear in the text box more than once.

    >alt the programme and return not to your code but to the form itself. -If you can'tsee your form, right:click Form"-csin the "olution Fxplorer on the right. (romthe menu that appears, select View esigner./

    )ow double click button 6, and add the following code0

    txt9isplay.Text N txt9isplay.Text btnTwo.TextA

    The only thing that's different is the name of the button : btnTwoinstead ofbtnGne. The rest is the same.

    9o the same for the rest of your button, changing the name of the button eachtime. -You can copy and paste your code to save time./

    ut your coding window should look like this, when you've finished0

    55

  • 8/13/2019 2 C# .NET Variables

    56/61

    Gun your programme again, and click all ten of your buttons. =ake sure thateach number appears in the text box when its button is clicked.

    56

  • 8/13/2019 2 C# .NET Variables

    57/61

  • 8/13/2019 2 C# .NET Variables

    58/61

    we need to give it what's knows as global scope. This is fairly easy : #ust set it upoutside of any buttons. $ike this0

    &ouble total" , A.

    !rivate voi& btnPlus)ClicKobject sen&er 7ventrgs e$

    M

    )ow the variable is outside of the curly brackets, making it available to all thebuttons on out form. "o set up that variable in your own code.

    (or the btnPluscode itself, add the following two lines -in blue bold below/0

    &ouble total" , A.

    !rivate voi& btnPlus)ClicKobject sen&er 7ventrgs e$

    total" , total" 6 &ouble-Parse txtis!la(-Text $.txtis!la(-Clear$.

    M

    *ll we're doing here is getting the text from the text box, converting it to a doublenumber, and then storing it in the total3 variable. )otice that we've also done this0

    total" , total" 6

    Hust like we did for the number buttons, we need to keep whatever was in thetotal"variable. You need to do this in case you want to add more than twonumbers. If you didn't keep what was in the total3 variable, & would BforgetBwhat was in it, and start afresh. This techniue is so common in programmingthat a shorthand way of doing this is usually implemented0

    total" 6, &ouble-Parsetxtis!la(-Text$.

    "o instead of repeating the variable name, you #ust use a plus symbol and aneuals symbol together - N /. The above line does exactly the same thing asthis0

    total" , total" 6 &ouble-Parsetxtis!la(-Text$.

    ut whichever way you choose to retain a value in a variable, all you're saying isBeep whatever is already in the variable, and add something elseB.

    58

  • 8/13/2019 2 C# .NET Variables

    59/61

    *fter storing the number from the text box, we need to clear it0

    txtis!la(-Clear $.

    +nce the text box is cleared, a second number can be selected by clicking the

    number buttons.

    In the next part, you'll learn how to code for the Fuals button.

    C# Calculator < T'e 7/uals Button

    @@ &ontinues from the previous section

    The Fuals button is where the action takes place. This is where we will do theactual addition.

    To store the answer to the addition, we'll need another variable -in blue boldbelow/0

    &ouble total" , A.

    &ouble total* , A.

    !rivate voi& btnPlus)ClicKobject sen&er 7ventrgs e$

    total" , total" 6 &ouble-Parsetxtis!la(-Text$.txtis!la(-Clear$.

    M

    "o set up a total*variable in your code, as we've done above.

    Geturn to your (orm, and double click the Fuals button to get at your code. )owadd the following three lines of code0

    total* , total" 6 &ouble-Parse txtis!la(-Text $.txtis!la(-Text , total*-ToString $.total" , A.

    The first line should look familiar0

    total6 N total3 &ouble-Parsetxt9isplay.Text $A

    To the right of the euals sign, we're doing the same thing as before0

    59

    http://www.homeandlearn.co.uk/csharp/csharp_s2p17.htmlhttp://www.homeandlearn.co.uk/csharp/csharp_s2p17.html
  • 8/13/2019 2 C# .NET Variables

    60/61

    total" 6 &ouble-Parsetxtis!la(-Text$.

    The difference is before the euals sign0 we're now storing it in the total6variable0

    total*N total3 double.Parse-txt9isplay.Text/A

    In other words, get the number from the text box, convert it to a double variable,add it to whatever is in total3. !hen all this is worked out, store the answer in thevariable called total6.

    The second line of code was this0

    txtis!la(-Text , total*-ToString $.

    +n the right of the euals sign, we're converting the total*variable To a "tring.

    This is so that it can be displayed as Text in the text box.

    The third line of code resets the total3 variable to

  • 8/13/2019 2 C# .NET Variables

    61/61