Using Selection More variables types object char Date

Using Selection

More variables types. . . object, char, Date. Time bool – containing the Boolean values of true and false More C# operators. . . relational logical Making decisions. . . the importance of selection or branching in programming using the if and switch statements Some more GUI controls. . . Check. Box, Radio. Button and Group. Box

you are already familiar with int, float, double, and decimal here a few more C# data types you should know of: object variables – store a ‘reference’ to an object (technically, a 4 -byte address of the computer memory location where the object code resides) char – store an individual character (using 2 bytes) – they are declared inside ‘single quotes’, whereas strings use “double quotes” Date. Time storing and manipulating dates and times can be difficult C# provides the Date. Time type to help a wealth of Methods to help create and manipulate dates & times

Date. Time - a few examples of its many capabilities: Date. Time my. Birthday = new Date. Time(1980, 05, 01); Date. Time time. Now = Date. Time. Now; Date. Time yesterday = new Date. Time(); yesterday = time. Now. Add. Days(-1. 0); //get current date //create empty Date. Time //compute relative date Message. Box. Show(Date. Time. Today. Add. Days(-7). To. String()); Message. Box. Show(yesterday. To. String()); Message. Box. Show(my. Birthday. To. String("D")); //format output

bool - stores (in 1 byte) only the value true or false, and can be assigned the values of expressions that evaluate to a Boolean value. widely used to test conditions and to determine program flow they are closely associated with: the relational operators the logical operators and the branching statement if

C# relational operators we’ve already seen the mathematical operators, +. -, *, and / these relational ops are used for performing comparisons between operands. they evaluate to a Boolean result – either true or false x == y x < y x > y x <= y x != y equality: returns true if X is equal to Y less than: returns true if X is less than Y greater than: returns true of X is greater than Y is less than or equal to is more than or equal to not equal: returns true if X is not equal to Y

C# logical operators apply Boolean logic to bool operands use to build more complex conditional tests they evaluate to a Boolean result – either true or false x && y x || y !x x ^y AND: returns true if both X and Y are true OR: returns true if either X or Y is true NOT: inverts current value; not true is false, etc XOR: returns true of X or Y is true, but not both

a few examples. . . int a=25; int b=56; int c=56; int d=82; (a < d) (d<= c) (b <=c && d < c) (a >=b || c <= d) (b == c) (a != c) //true //false //true

Decisions, decisions… the IF word

Decisions decisions… So far, your programs have operated a little like glorified calculators - they have executed sets of sequential instructions, initiated by events Most useful programs need to make decisions and to undertake different courses of action depending on the data and the conditions that are presented to them

Conditional statements allow your program to take different paths through the code, to perform different actions depending on current data values, or perhaps in response to errors (exceptions) C# has two primary decision structures… if… switch. . .

if if ( ) { } general syntax the keyword if is followed by a pair of round brackets, between which you type the condition you wish to test then, conveniently (but not strictly necessary) a pair of braces, between which you place the code that is to run if the condition evaluates to true

if (condition) is an expression that evaluates to the value of true or false, or possibly a variable or property of type bool we’ve already seen that bool variables can hold the values true or false so we could code an if statement up as something like. . . bool some. Variable = true; if (some. Variable) { Message. Box. Show(“This code will be executed”); }

if although an if can test the value of a bool variable directly (as in the last example), more often they will test an expression. . . if (this. Variable > that. Variable) { //some appropriate code placed here. . . } so the relational and logical operators seen earlier are likely to appear in such an expression which evaluates to true or false

if many GUI objects (and other objects) have properties that are of type bool, so it is possible to see coding something like this. . . if (text. Box 1. Read. Only) { Message. Box. Show(“This text cannot be edited”); } or this equivalent coding. . if (text. Box 1. Read. Only == true) { Message. Box. Show(“This text cannot be edited”); }

if Here is another typical example of using an if construct. . . if (text. Box 1. Text. Length == 0) { Message. Box. Show(“The text box is empty!”); }

Using conditional operators care is needed as it is quite easy to fall into this trap if (button. Clicked = = true) (will test for equality) is very different from. . . if (button. Clicked = true) (will assign the value true to the variable and so this will always be true) and note that these two are equivalents. . . if (button. Clicked != true) if (button. Clicked == false)

Some more GUI controls this is convenient point to introduce a few more GUI controls… – Check Boxes – Radio Buttons – Group Controls the first two are primarily used to gather information (often choices or options) from the user, and since their most important property is of type bool are often used in conjunction with selection statements

Check Boxes mainly used to gather input where the user has a binary choice: Yes / No True / False On / Off etc. each check box operates independently of all others on a form so a user can place a tick next to none, more, or all check boxes

Checkbox Useful properties Auto. Size Checked Enabled Name Image Text. Align Visible its most important property is Checked which is of type bool and reflects its current ticked status the Text property controls the associated text (you can also use or add images) naming convention is to use the prefix chk

Check Box Properties the Checked Property may be set at Design Time using the Properties panel . . . or can be manipulated during program execution. . chk. Freesia. Checked = true; chk. Lilies. Checked = false;

Using Check Boxes with if statements since the Checked property is type bool we can query it directly with an if statement and use to control program flow if (chk. Roses. Checked) { // do what is necessary here }. . . or you may see something like. . . if (chk. Lillies. Checked == false) { //put code here for execution }

Radio buttons are mainly used to gather input, especially associated with the selection of mutually-exclusive options unlike check boxes, radio buttons on a form interact with each other – only one can be selected at any one time - selecting any one automatically deselects all others

Radio button Useful properties Checked Enabled Name Image Text. Align Visible again its most important property is Checked of type bool, which reflects its current status the Text property controls the associated text (you can also use or add images) naming convention is to use the prefix rad or opt

• R when first placed onto a form they are unchecked (checked == false), but logically one control should always be initialised to be in a checked state just make sure you set one as being checked by using the Properties panel or you can set one as checked via code radio. Button 1. Checked = true; often used with branching statements. . . if (radio. Button 2. Checked) { //do something here. . . }

Group Controls associated with radio buttons are the Group. Box control and other so-called ‘container’ objects. . . radio buttons are often placed into a Group. Box then one radio button in each group may be selected thus allowing several groups of buttons to coexist on the same form place the Group Box on the form first, and then place the radio buttons inside of it

Example in this example a Group. Box contains one set of radio buttons depicting the selection of payment method, while another Group. Box lists the delivery options available a Group. Box should have its Text property (which is displayed in the border) set to provide a useful indication of its purpose note: here one choice can be selected from within each group

You will have some examples of deploying Checkbox, Radio. Button and Group. Box controls demonstrated to you.

Making more complex decisions… Often, we want to do one set of actions if something does occur, or do some other set of actions if it does not… Consider the example of a car driver – if the traffic light ahead is red light you must stop, but if it is green you should carry on moving

if. . . else easily solved in C# using the else keyword if (condition) { } else { } for example. . . if (text. Box 1. Text. Length == 0) { Message. Box. Show(“Text box was empty”); } else { Message. Box. Show(text. Box 1. Text); }

multiple conditions can be tested using else if if (condition) { //some code. . . } else if (different_condition) { //some different code. . . } else if (another_condition) { //different code again. . . } else { //this will execute if none of the above are true }

be careful – the order of testing can be important if (score < 40) { result = ‘Failed’; } else if (score < 60) { result = ‘Passed’; } else if (score < 70) { result = ‘Merit’; } else result = ‘First Class’; } if (score < 70) { result = ‘Merit’; } else if (score < 40) { result = ‘Failed’; } else if (score < 60) { result = ‘Passed’; } else result = ‘First Class’; }

if necessary conditions can be ‘nested’ i. e. one set of decisions sits inside the branch of another

you can use as many else if statements as are needed to provide alternative choices. . . if (condition) {statements} else if (condition) {statements} . . . but this does become cumbersome and makes code difficult to read and understand else if (condition) {statements} else {statements}

the Switch statement if faced with lots of conditions to test, a switch statement is often the preferred coding method switch ( ) { case test 1 : //statements here break; case test 2 : //statements here break; default : //this bit is optional break; }

the syntax of switch needs some care: after the word switch are round brackets inside of which you type what you want to check - usually the current value of a variable followed by a pair of curly brackets { } then one or more case statements each listing a possible value your variable might contain and ending in “: ” followed by the code to be executed if that case is matched; and ending with the keyword break (essential to enable C# to break out of the switch) you may optionally add a default statement to pick up any values not covered by the case statements

switch statement although similar to if… else if it can make code more readable there is also a subtle difference if… else if can evaluate a different condition in each test switch tests the value of a single expression or variable, which is then used repeatedly in each comparison that follows

string the. Operator; private void btn. Plus_Click(object sender, Event. Args e) { total += double. Parse(txt. Display. Text); txt. Display. Clear(); switch (the. Operator) the. Operator = "+"; { } case "+" : //Addition Code Here break; case "-" : for example – it can //Subtraction Code Here help to make your break; calculator program case "*": much more readable. . . //Multiply Code Here break; case “/": //Divide Code Here break; }
- Slides: 38