Week 6: THE C# LANGUAGE
description
Transcript of Week 6: THE C# LANGUAGE
C#4.0Week 6:
THE C# LANGUAGE
Flow Control
C#4.0
Slide 2
Data Types
Boolean Byte (0 to 255) Char Date String Decimal Object
Short (-32,768 to 32,767) Integer (-2,147,483,648 to
2,147,483,647) Long (larger whole numbers) Single (floating point accuracy
to 6 digits) Double (floating point accuracy
to 14 points)
C#4.0
Slide 3
Data Types – Memory Usage
Boolean – 1 bytes Byte – 1 byte Char – 2 bytes Date – 8 bytes String – varies Decimal – 16 bytes Object –
Short – 2 bytes Integer – 4 bytes Long – 8 bytes Single – 4 bytes Double – 8 bytes
C#4.0
Slide 4
Data Types – Prefixes
Boolean – bln Byte – byt Char – chr Date – dat String – str Decimal – dec Object – depends
on type of object
Short – sht Integer – int Long – lng Single – sng Double – dbl
C#4.0
Slide 5
Declaration Statements Declare Variables
int intNumberOfStudents ; CONST used to declare Named Constants
Const single sngDISCOUNT_RATE = 0.2f; Declaration includes
Name, follow Naming Convention Rules Data Type Required Value for Constants Optional Initial Value for Variables
C#4.0
Slide 6
Type-Declaration Characters Append single character to the end of the
Constant's Value to indicate the Data Type• Decimal – m • Single – F• Double
Const Single sngDISCOUNT_RATE = 0.2F;
C#4.0
Slide 7
Declaration Examples
string strName, strSSN ;int intAge; decimal decPayRate ;decimal decTax=0.1M ;bool blnInsured ;long lngPopulation ;decimal decDT, decCD, decCR;decimal decHour, decSumSal, decDiemTB, decSum=0;decimal decTax = 0.12M, decHSLuong=3.16M;const decimal decDISCOUNT_RATE = 0.15M;
C#4.0
Slide 8
Scope Declaring & Naming (*)
Public g prefix Declare in General Declarations as Public
Module/Private m prefix Declare in Module’s General Declarations as Private
Local no prefix required Declare in Event Procedures
String gstrName ;
String mstrName;
String strName ;
C#4.0
Slide 9
Scope Public
Available to all modules and procedures of Project Module/Private (Form)
Can be used in any procedure on a specific Form, but is not visible to other Forms
Initialized 1st time the Form is loaded Local
Available only to the procedure it is declared in Initialized every time the Procedure runs
Block (not used until later in this course) Available only to the block of code inside a procedure it is
declared in Initialized every time the Procedure runs
C#4.0
Slide 10
Declaring Local Level Variables Example
Local Level Variables
C#4.0
Slide 11
Declaring Module Level Variables Example
Module - Level Variables and Constants
C#4.0
Slide 12
Declaring Block Level Variables Example
int a,b;
if (a > b)
{
int max;
max = a;
}
else
{
int max1;
max1=max Được không??
max1 = b;
}
Block Level Variables
Block Level Variables
C#4.0
Slide 13
Math Class Methods (p 192) The Math class
Allows the user to perform common math calculations
Using methodsClassName.MethodName( argument1,
arument2, … ) Constants
Math.PI = 3.1415926535…Math.E = 2.7182818285…
C#4.0
Slide 14
9:06:37 AM
Math Class MethodsMethod Example Abs( x ) Abs( 23.7 ) is 23.7 Ceiling( x ) Ceiling( 9.2 ) is 10.0
Ceiling( -9.8 ) is -9.0 Cos( x ) Cos( 0.0 ) is 1.0
Exp( x ) Exp( 1.0 ) is approximately 2.7182818284590451
Floor( x ) Floor( 9.2 ) is 9.0 Floor( -9.8 ) is -10.0
Log( x ) Log( 2.7182818284590451 ) is approximately 1.0
Max( x, y ) Max( 2.3, 12.7 ) is 12.7 Max( -2.3, -12.7 ) is -2.3
Min( x, y ) Min( 2.3, 12.7 ) is 2.3 Min( -2.3, -12.7 ) is -12.7
C#4.0
Slide 15
Math Class Methods
Method ExamplePow(x,y) Pow( 2.0, 7.0 ) is 128.0
Pow( 9.0, .5 ) is 3.0
Sin ( x ) Sin( 0.0 ) is 0.0
Sqrt ( x ) Sqrt( 900.0 ) is 30.0Sqrt( 9.0 ) is 3.0
Tan ( x ) Tan( 0.0 ) is 0.0
C#4.0
Slide 16
Compound Assignment Operators Assignment operators
Can reduce code x += 2 is the same as x = x + 2
Can be done with all the math operators ++, -=, *=, /=, and %=
C#4.0
Slide 17
Assignment OperatorsAssignment operator Sample expression Explanation Assigns Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g Arithmetic assignment operators.
C#4.0
Slide 18
Increment and Decrement Operators Increment operator
Used to add one to the variable x++ Same as x = x + 1
Decrement operator Used to subtract 1 from the variable y--
C#4.0
Increment and Decrement Operators Pre-increment vs. post-increment
x++ or x-- Will perform an action and then add to or subtract one
from the value ++x or --x
Will add to or subtract one from the value and then perform an action
Windows Programming 1 Slide 19
C#4.0
Slide 20
Increment and Decrement Operators
Operator Called Sample expression Explanation ++ preincrement ++a Increment a by 1, then use the new value
of a in the expression in which a resides.
++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.
-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.
Fig. 5.13 The increment and decrement operators.
C#4.0
Slide 21
Increment and Decrement Operators
Operators Associativity Type () ++ --
left to right right to left
parentheses unary postfix
++ -- + - (type) right to left unary prefix
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= %= right to left assignment
Precedence and associativity of the operators discussed so far in this book.
C#4.0
Slide 22
Format CodeFormat Code Description
C or c Formats the string as currency. Precedes the number with an appropriate currency symbol ($ in the US).
D or d Formats the string as a decimal. Displays number as an integer.
N or n Formats the string with commas and two decimal places.
E or e Formats the number using scientific notation with a default of six decimal places.( 14000 = 1, 4 x 10 Ư 4)
F or f Formats the string with a fixed number of decimal places (two by default).
G or g General. Either E or F.
X or x Formats the string as hexadecimal.
C#4.0
Slide 23
Example
lblCommission.Text =
string.Format("{0:C}",decCommission);
C#4.0
Slide 24
Format Code
C#4.0
Slide 25
Logical and Conditional Operators Operators
Logical AND (&) Conditional AND (&&) Logical OR (|) Conditional OR (||) Logical exclusive OR or XOR (^) Logical NOT (!)
Can be avoided if desired by using other conditional operators
Used to add multiple conditions to a statement
C#4.0
Slide 26
Logical and Conditional Operatorsexpression1 expression2 expression1 &&
expression2 false false false false true false true false false true true true Truth table for the && (logical AND) operator. expression1 expression2 expression1 ||
expression2 false false false false true true true false true true true true Truth table for the || (logical OR) operator.
C#4.0
Slide 27
Logical and Conditional Operatorsexpression1 expression2 expression1 ^
expression2 false false false false true true true false true true true false Truth table for the logical exclusive OR (^) operator. expression !expression false true True false Truth table for operator! (logical NOT).
C#4.0
Slide 28
Structured Programming Summary
Operators Associativity Type () ++ --
left to right right to left
parentheses unary postfix
++ -- + - ! (type) right to left unary prefix
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
& left to right logical AND
^ left to right logical exclusive OR
| left to right logical inclusive OR
&& left to right conditional AND
|| left to right conditional OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Precedence and associativity of the operators discussed so far.
C#4.0
Slide 29
Mathematical Examples
Thứ tự thưc hiện
C#4.0
Slide 30
Control Structures Program of control
Program performs one statement then goes to next line Sequential execution
Different statement other than the next one executes Selection structure
The if and if/else statements The goto statement
No longer used unless absolutely needed Causes many readability problems
Repetition structure The while and do/while loops (chapter 5) The for and foreach loops (chapter 5)
C#4.0
Slide 31
Control Structures
add grade to total
add 1 to counter
total = total + grade;
counter = counter + 1;
Fig. 5.1 Flowcharting C#’s sequence structure.
C#4.0
Slide 32
if Selection Structure The if structure
Causes the program to make a selection Chooses based on conditional
Any expression that evaluates to a bool type True: perform an action False: skip the action
Single entry/exit point Require no semicolon in syntax
C#4.0
Slide 33
if Selection Structure
Fig. 5.3 Flowcharting a single-selection if structure.
do somethingconditionstrue
false
C#4.0
Slide 34
if/else selection structure The if/else structure
Alternate courses can be taken when the statement is false
Rather than one action there are two choices Nested structures can test many cases Structures with many lines of code need braces
({) Can cause errors
Fatal logic error Nonfatal logic error
C#4.0
Slide 35
if/else Selection Structure
Fig. 5.4 Flowcharting a double-selection if/else structure.
Conditions
do somethingdo something else
false true
C#4.0
Slide 36
Conditional Operator (?:) Conditional Operator (?:)
C#’s only ternary operator Similar to an if/else structure The syntax is:
boolean value ? if true : if false
Console.WriteLine( grade >= 60 ? "Passed" : "Failed" );
C#4.0
Slide 37
Loops Repeating a series of instructions Each repetition is called an iteration Types of Loops
Do Use when the number of iterations is unknown
For Use when the number of iterations known
C#4.0
Slide 38
while Repetition Structure
Fig. 4.5 Flowcharting the while repetition structure.
true
false
do somethingconditions
C#4.0
Slide 39
for Repetition Structure The for repetition structure
Syntax:for (Expression1, Expression2, Expression3) Expression1 = names the control variable
Can contain several variables Expression2 = loop-continuation condition Expression3 = incrementing/decrementing
If Expression1 has several variables, Expression3 must have several variables accordingly
++counter and counter++ are equivalent
C#4.0
Slide 40
9:06:37 AM
for Repetition Structure
for ( int counter = 1; counter <= 5; counter++ )
Initial value of control variable Increment of control variable
Control variable name Final value of control variablefor keyword
Loop-continuation condition
Fig. 5.3 Components of a typical for header.
C#4.0
Slide 41
for Repetition Structure
counter++
Establish initial value of control variable.
Determine if final value of control variable has been reached.
counter <= 10 Console.WriteLine( counter * 10 );
true
false
int counter = 1
Body of loop (this may be multiple statements)
Increment the control variable.
Fig. 5.4 Flowcharting a typical for repetition structure.
C#4.0
Slide 42
switch Multiple-Selection Structure
switch (<Biểu Thức>){ Case Giá trị 1 :
[ code to run] break;
Case Giá trị 2 : [ code to run]
break;[default ]
[code to run]]}
If expression=value in constant list
If expression< >values in any of the preceding constant lists
C#4.0
Slide 43
Flocharting Switch Multiple Selection Structure.
Case a: Actions a break;
Case b: Actions b break;
Case n: Action n break;
default break;
true
true
true
true
false
false
false
C#4.0
Slide 44
SwitchCase - Numeric Value Example 1switch ( intScore) { case 100:
lblMsg.Text="Excellent Score"; break; case 99:
lblMsg.Text="Very Good"; break; case 79:
lblMsg.Text="Excellent Score"; break; default:
lblMsg.Text="Improvement Needed"; break; }
C#4.0
Slide 45
9:06:37 AM
do/while Repetition Structure The while loops vs. the do/while loops
Using a while loop Condition is tested The the action is performed Loop could be skipped altogether
Using a do/while loop Action is performed Then the loop condition is tested Loop must be run though once Always uses brackets ({) to prevent confusion
C#4.0
Slide 46
do/while Repetition Structure
true
false
action(s)
condition
Fig. 5.13 Flowcharting the do/while repetition structure.
C#4.0
Slide 47
9:06:37 AM
MessageBox Object Use Show Method of MessageBox to display
special type of window Arguments of Show method
Message to display Optional Title Bar Caption Optional Button(s) Optional Icon
C#4.0
Slide 48
9:06:37 AM
MessageBox Syntax
MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)
The MessageBox is an Overloaded Method Overloading – ability to call different versions of a procedure
based on the number and data types of the arguments passed to that procedure
The number and data types of the arguments expected by a procedure are called Signatures
There are multiple Signatures to choose from Arguments must be included to exactly match one of the
predefined Signatures
C#4.0
Slide 49
9:06:37 AM
MessageBoxIcon ConstantsMessageBox Icons Icon Description MessageBoxIcon.Exclamation
Displays a dialog with an exclamation point. Typically used to caution the user against potential problems.
MessageBoxIcon.Information
Displays a dialog with an informational message to the user.
MessageBoxIcon.Question
Displays a dialog with a question mark. Typically used to ask the user a question.
MessageBoxIcon.Error
Displays a dialog with an x in a red circle. Helps alert user of errors or important messages.
Fig. 5.6 Icons for message dialogs.
C#4.0
Slide 50
9:06:37 AM
MessageBoxButtonMessageBox Buttons Description MessageBoxButton.OK Specifies that the dialog should
include an OK button.
MessageBoxButton.OKCancel Specifies that the dialog should include OK and Cancel buttons. Warns the user about some condition and allows the user to either continue or cancel an operation.
MessageBoxButton.YesNo Specifies that the dialog should contain Yes and No buttons. Used to ask the user a question.
MessageBoxButton.YesNoCancel Specifies that the dialog should contain Yes, No and Cancel buttons. Typically used to ask the user a question but still allows the user to cancel the operation.
MessageBoxButton.RetryCancel Specifies that the dialog should contain Retry and Cancel buttons. Typically used to inform a user about a failed operation and allow the user to retry or cancel the operation.
MessageBoxButton.AbortRetryIgnore Specifies that the dialog should contain Abort, Retry and Ignore buttons. Typically used to inform the user that one of a series of operations has failed and allow the user to abort the series of operations, retry the failed operation or ignore the failed operation and continue.
Fig. 5.7 Buttons for message dialogs.
C#4.0
Slide 51
ExDialogResult dl; dl= MessageBox.Show( "Are you sure exit ? ",
"Warning" , MessageBoxButtons.YesNo,
MessageBoxIcon.Question);if (dl == DialogResult.Yes) Close();
C#4.0Week 6:
THE C# LANGUAGE
More Variable
C#4.0
Value types and reference types The .NET type system defines two categories
of data type Value types
Values stored on the stack Derived from System.ValueType Examples of built-in framework value types:
Byte, Int16, Int32, Int64, Single, Double, Decimal, Char, Boolean
C# has built-in types which are aliases for these: byte, short, int, long, float, double, decimal, char, bool
Object Oriented Software Development 53
C#4.0
Value types and reference types Reference types
Objects stored in the heap References stored on the stack Types derived from System.Object Examples of reference types:
String (C# alias is string) all classes, including classes in your project arrays (see later) delegates (see later)
Object Oriented Software Development 54
C#4.0
Boxing and unboxing Boxing
Converting value type to reference type
Unboxing Converting reference type to value type
We will look again at boxing and type conversions later
Object Oriented Software Development 4. C# data types, objects and references
55
C#4.0
Creating value types There are two kinds of value type in .NET struct
Similar to a class, but stored as a value type Local variable of struct type will be stored on the
stack Built-in values types, e.g. Int32, are structs
enum An enumeration type Consists of a set of named constants
Object Oriented Software Development 56
C#4.0
struct Example in TimeSheet.cs - rewrite
TimeSheet as a struct rather than a class
struct can contain instance variables, constructors, properties, methods
Can’t explicitly declare default constructor Compiler generates default constructor
Object Oriented Software Development 57
C#4.0
struct Instance can be created without new key
word
With class, this would create a null reference With struct, this creates instance with fields
set to default values
This explicitly calls default constructor
Object Oriented Software Development 58
C#4.0
Method call with struct parameter Revisit earlier example with TimeSheet as a
struct Main creates TimeSheet struct
instance and passes it as a parameter to RecordOvertime Parameter contains a copy of
the struct A copy of whole struct placed
on stack
Object Oriented Software Development 4. C# data types, objects and references
59
Stack
Program.Main
emp1:Employeeloc: Location
emp2:Employee
ts: TimeSheetEmployee.RecordOvertime
hours: intisWeekend: bool
copy
numberOfEntries: intmaxEntries: int
ts: TimeSheetnumberOfEntries: int
maxEntries: int
C#4.0
struct vs. class TimeSheet example is a small struct, but
structs can have large numbers of instance variables
Passing large structs as parameters can use a lot of stack memory
On the other hand, creating objects on the heap is expensive in terms of performance compared to creating structs
No definitive rules, but take these factors into account when deciding
Object Oriented Software Development 4. C# data types, objects and references
60
C#4.0
enum enum is a good way of storing and naming
constant values
Enum has an underlying data type int by default in example, Days.Sat, Days.Sun, Days.Mon...
represent values 0,1, 2,... can set values explicitly
Object Oriented Software Development 4. C# data types, objects and references
61
C#4.0
enum example Previously indicated pay rate with boolean
value isWeekend Replace this with enum, which allows more
than simply true/false
Object Oriented Software Development 62
C#4.0
enum example Change parameter in RecordOvertime to type
PayRate
Object Oriented Software Development 63
C#4.0
enum example Pass in enumeration value to method
Always refer to value by name, don’t need to know or use underlying value
Object Oriented Software Development 64
C#4.0
Warning! Classes, objects, instance variables,
methods, references are fundamental OO concepts
Value types (struct, enum) and properties are specific to the way in which .NET interprets the OO programming model
Object Oriented Software Development 65