week 6 the c language n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Week 6: THE C# LANGUAGE PowerPoint Presentation
Download Presentation
Week 6: THE C# LANGUAGE

Loading in 2 Seconds...

play fullscreen
1 / 65

Week 6: THE C# LANGUAGE - PowerPoint PPT Presentation


  • 48 Views
  • Uploaded on

Week 6: THE C# LANGUAGE. Flow Control. 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)

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Week 6: THE C# LANGUAGE' - lee


Download Now An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
data types
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)
data types memory usage
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
data types prefixes
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
declaration statements
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
type declaration characters
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;

declaration examples
Declaration Examples

stringstrName, strSSN ;

intintAge;

decimaldecPayRate ;

decimaldecTax=0.1M ;

boolblnInsured ;

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;

scope declaring naming
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 ;
scope
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
declaring block level variables example

Block Level Variables

Block Level Variables

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;

}

math class methods p 192
Math Class Methods (p 192)
  • The Math class
    • Allows the user to perform common math calculations
    • Using methods
      • ClassName.MethodName( argument1, arument2, … )
    • Constants
      • Math.PI = 3.1415926535…
      • Math.E = 2.7182818285…
compound assignment operators
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 %=
increment and decrement operators
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--
increment and decrement operators1
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

example
Example
  • lblCommission.Text = string.Format("{0:C}",decCommission);
logical and conditional operators
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
control structures
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)
control structures1

add grade to total

total = total + grade;

add 1 to counter

counter = counter + 1;

Control Structures

Fig. 5.1 Flowcharting C#’s sequence structure.

if selection structure
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
if selection structure1

conditions

do something

true

false

if Selection Structure

Fig. 5.3 Flowcharting a single-selection if structure.

if else selection structure
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
if else selection structure1

false

true

Conditions

do something else

do something

if/else Selection Structure

Fig. 5.4 Flowcharting a double-selection if/else structure.

conditional operator
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" );

loops
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
while repetition structure

conditions

true

do something

false

while Repetition Structure

Fig. 4.5 Flowcharting the while repetition structure.

for repetition structure
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
for repetition structure1

for

keyword

Control variable

name

Final value

of control variable

for

(

int

counter = 1; counter <= 5; counter++ )

Initial value

of control variable

Increment

of control variable

Loop-continuation condition

for Repetition Structure

Fig. 5.3 Components of a typical for header.

for repetition structure2
for Repetition Structure

Establish initial value of control variable.

int counter = 1

Determine if final value of control variable has been reached.

true

Console.WriteLine

counter <= 10

counter++

( counter * 10 );

Increment the control variable.

false

Body of loop (this may be multiple statements)

Fig. 5.4 Flowcharting a typical for repetition structure.

switch multiple selection structure
switch Multiple-Selection Structure

switch(<Biểu Thức>)

{

CaseGiá trị 1 :

[ code to run]

break;

CaseGiá 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

flocharting switch multiple selection structure

true

Case a:

Actions a

break;

false

true

Case b:

Actions b

break;

false

true

Case n:

Action n

break;

false

true

default

break;

Flocharting Switch Multiple Selection Structure.
switchcase numeric value example 1
SwitchCase - Numeric Value Example 1

switch ( 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;

}

do while repetition structure
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
do while repetition structure1

action(s)

true

condition

false

do/while Repetition Structure

Fig. 5.13 Flowcharting the do/while repetition structure.

messagebox object
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
messagebox syntax
MessageBox Syntax
  • 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

MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)

slide51
Ex

DialogResult dl;

dl= MessageBox.Show( "Are you sure exit ? ","Warning" ,MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if (dl == DialogResult.Yes)

Close();

value types and reference types
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

value types and reference types1
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

boxing and unboxing
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

creating value types
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

struct
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

struct1
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

method call with struct parameter
Method call with struct parameter
  • Revisit earlier example with TimeSheet as a struct
  • Main creates TimeSheet structinstance 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

struct vs class
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

slide61
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

enum example
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

enum example1
enum example

Change parameter in RecordOvertime to type PayRate

Object Oriented Software Development 63

enum example2
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

warning
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