Tải bản đầy đủ - 0 (trang)
Hour 14. Making Decisions in C# Code

Hour 14. Making Decisions in C# Code

Tải bản đầy đủ - 0trang

Hour14.MakingDecisionsinC#Code

InHour11,"CreatingandCallingMethods,"youlearnedhowto

separate code into multiple methods to be called in any order

required. But if you had to separate each small code routine

into its own method, your projects would quickly become

unmanageable.Insteadofcreatingnumerousmethods,youcan

usedecision-makingtechniquestoexecuteoromitspecificlines

of code within a single method. Decision-making constructs or

codingstructuresallowyoutoexecute(oromit)codebasedon

the current situation, such as the value of a variable. C#

includes two constructs that allow you to make any type of

branchingdecisionyoucanthinkof:if…elseandswitch.

In this hour, you'll learn how to use the decision constructs

provided by C# to perform robust yet efficient decisions in C#

code.Inaddition,you'lllearnhowtousethegotostatementto

redirectcode.You'llprobablycreatedecisionconstructsinevery

applicationyoubuild,sothequickeryoumastertheseskills,the

easieritwillbetocreaterobustapplications.

Thehighlightsofthishourincludethefollowing:

Makingdecisionsusingifstatements

Expandingthecapabilityofifstatementsusingelse

Evaluating an expression for multiple values using the

switchstatement

Redirectingcodeflowusinggoto







Top











MakingDecisionsUsingifStatements

By far the most common decision-making construct used in

programmingistheifconstruct.Asimpleifconstructlookslike

this:



if(expression)

...statementtoexecutewhenexpressionistrue;

The if construct uses Boolean logic, as discussed in Hour 13,

"Performing Arithmetic, String Manipulation, and Date/Time

Adjustments,"toevaluateanexpressiontoeithertrueorfalse.

Theexpressionmaybesimple(if(x==6))orcomplicated

(if (x==6 && y>10)). If the expression evaluates to true,

the statement or block of statements (if enclosed in braces)

getsexecuted.Iftheexpressionevaluatestofalse,C#doesn't

executethestatementorstatementblockfortheifconstruct.



Rememberthatcompound,alsofrequentlycalledblock

statements, can be used anywhere a statement is

expected. A compound statement consists of zero or

morestatementsenclosedinbraces({}).Followingis

anexampleoftheifconstructusingablockstatement:

if(expression)

{

statement1toexecutewhenexpressionistrue;

statement2toexecutewhenexpressionistrue;

...statementntoexecutewhenexpressionistrue;

}



You're going to create a simple if construct in a C# project.

Create a new Windows Application named Decisions. Rename

thedefaultformtofclsDecisions,settheTextpropertyofthe

formtoDecisionsExample,andupdatetheentrypointMain()

toreferencefclsDecisionsinsteadofForm1.

Addanewtextboxtotheformbydouble-clickingtheTextbox

icon in the toolbox. Set the properties of the text box as

follows:

Property



Value



Name

Location

Text



txtInput

44,44

(makeblank)



Next, add a new button to the form by double-clicking the

Button icon in the toolbox. Set the button's properties as

follows:

Property



Value



Name

Location

Size

Text



btnIsLessThanHundred

156,42

100,23

Istext<100?



YourformshouldnowlookliketheoneinFigure14.1.

Figure14.1.You'llusetheifstatementtodetermine

whetherthevalueofthetextenteredintothetextboxis

lessthan100.



You're now going to add code to the button's Click event. This

code will use a simple if construct and the int.Parse() method.

Theint.Parse()methodisusedtoconverttextintoitsnumeric

equivalent,andyou'lluseittoconvertthetextintxtInputinto

an integer. The if statement will then determine whether the

numberenteredintothetextboxislessthan100.Double-click

thebuttonnowtoaccessitsClickevent,andenterthefollowing

code:



if(int.Parse(txtInput.Text)<100)

MessageBox.Show("Thetextenteredislessthan10

This code is simple when examined one statement at a time.

Look closely at the first statement and recall that a simple if

statementlookslikethis:



if(expression)

statement;

Inthecodeyouentered,expressionis



int.Parse(txtInput.Text)<100

What you are doing is asking C# to evaluate whether the

parsed integer is less than 100. If it is, the evaluation returns

true.Ifthevalueisgreaterthanorequalto100,theexpression

returnsfalse.Iftheevaluationreturnstrue,executionproceeds

with the line immediately following the if statement and a

message is displayed. If the evaluation returns false, the line

statement (or block of statements) following the if statement

doesn'texecuteandnomessageisdisplayed.



Iftheuserleavesthetextboxemptyorentersastring,

anexceptionwillbethrown.Therefore,you'dnormally

implementexceptionhandlingaroundthistypeofcode.

You'll learn about exception handling in Hour 16,

"DebuggingYourCode."



ExecutingCodeWhenExpressionIsFalse

Ifyouwanttoexecutesomecodewhenexpressionevaluatesto

false,includetheoptionalelsekeyword,likethis:



if(expression)

statementtoexecutewhenexpressionistrue;

else

statementtoexecutewhenexpressionisfalse;

If you want to execute code only when expression

equates to false, not when true, use the not-equal

operator(!=) in the expression. Refer to Hour13for

moreinformationonBooleanlogic.



By including an else clause, you can have one or more

statements execute when expression is true and other

statements execute when the expression is false. In the

exampleyou'vebuilt,ifauserentersanumberlessthan100,

theuserwillgetamessage.However,ifthenumberisgreater

than or equal to 100, the user receives no feedback. Modify

yourcodetolooklikethefollowing,whichensuresthattheuser

alwaysgetsamessage:



if(int.Parse(txtInput.Text)<100)

MessageBox.Show("Thetextenteredislessthan100."

else

MessageBox.Show("Thetextenteredisgreaterthanor

Now, if the user enters a number less than 100, the message

The text entered is less than 100 is displayed, but

nothing more. When C# encounters the else statement, it

ignores the statement(s) associated with the else statement.

The statements for the else condition execute only when

expression is false. Likewise, if the user enters text that is

greater than or equal to 100, the message The text

entered is greater than or equal to 100 is

displayed, but nothing more; when expression evaluates to

false,executionimmediatelyjumpstotheelsestatement.

ClickSaveAllonthetoolbartosaveyourworkandthenpress

F5toruntheproject.Enteranumberintothetextboxandclick

the button. A message box appears, telling you whether the

number you entered is less than or greater than 100 (see

Figure14.2).

Figure14.2.Asimpliedwiththismessagebox,ifgives

yougreatflexibilityinmakingdecisions.



Feel free to enter other numbers and click the button as often

as you like. When you're satisfied that the code is working,

chooseStopDebuggingfromtheDebugmenu.



Get comfortable with if; chances are you'll include at

leastoneineveryprojectyoucreate.



NestingifConstructs

As mentioned earlier, you can nest if statements to further

refine your decision making. The format you use can be

somethinglikethefollowing:



if(expression1)

if(expression2)

...

else

...



else

...







Top











EvaluatinganExpressionforMultipleValuesUsing

switch

At times, the if construct isn't capable of handling a decision

situationwithoutalotofextrawork.Onesuchsituationiswhen

you need to perform different actions based on numerous

possible values of an expression, not just true or false. For

instance, suppose you wanted to perform actions based on a

user's profession. The following shows what you might create

usingif:



if(strProfession=="programmer")

...

elseif(strProfession=="teacher")

...

elseif(strProfession=="accountant")

...

else

...

Asyoucansee,thisstructurecanbeabithardtoread.Ifthe

number of supported professions increases, this type of

construction will get harder to read and debug. In addition,

executingmanyifstatementslikethisisratherinefficientfrom

aprocessingstandpoint.

Theimportantthingtorealizehereisthateachelse…ifisreally

evaluating the same expression (strProfession) but considering

different values for the expression. C# includes a much better

decisionconstructforevaluatingasingleexpressionformultiple

possiblevalues:switch.

Aswitchconstructlookslikethefollowing:



switch(expression)

{

casevalue1:

...

jump-statement

default:

...

jump-statement

}

defaultisusedtodefinecodethatexecutesonlywhen

expressiondoesn'tevaluatetoanyofthevaluesinthe

casestatements.Useofdefaultisoptional.

Here's the Profession example shown previously, but this time

switchisused:



switch(strProfession)

{

case"teacher":

MessageBox.Show("Youeducateouryoung");

break;

case"programmer":

MessageBox.Show("Youaremostlikelyageek");

break;

case"accountant":

MessageBox.Show("Youareabeancounter");

break;

default:

MessageBox.Show("Professioncurrentlynotsuppo

break;

}



The flow of the switch statement is as follows: When the case

expressionismatched,thecodestatementorstatementswithin

the case are executed. This must be followed by a jumpstatement, such as break, to transfer control out of the case

body.



If you create a case construct but fail to put code

statements or a jump-statement within the case,

execution will fall through to the next case statement,

eveniftheexpressiondoesn'tmatch.

The switch makes decisions much easier to follow. Again, the

keywithswitchisthatit'susedtoevaluateasingleexpression

formorethanonepossiblevalue.



BuildingaswitchExample

You're now going to build a project that uses expression

evaluation in a switch construct. This simple application will

display a list of animals in a combo box to the user. When the

user clicks a button, the application will display the number of

legsoftheanimalinthelist(ifananimalisselected).Createa

new Windows Application named Switch Example. Rename

the default form to flcsSwitchExample, set the form's Text

property to Switch Example, and update the entry point in

procedure Main() to reference flcsSwitchExample instead of

Form1.

Next,addanewcomboboxtotheformbydouble-clickingthe

ComboBoxitemonthetoolbox.Setthecombobox'sproperties

asfollows:

Property



Value



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hour 14. Making Decisions in C# Code

Tải bản đầy đủ ngay(0 tr)

×