You are on page 1of 27

2017S2 

ITP213

ITP213 @ 2017S2 
Enterprise Application Development
LECTURE 03
C# PROGRAMMING – PART 1

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 1

Learning outcome
Define appropriate C# data type for variables

Use operator for arithmetic operation

Use condition statement for decision making

Construct methods

Proper handle exception

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 2
2017S2 ITP213

C# Syntax – Variable Declaration
What are variables?
◦ Variables are names assigned by programmer, to store data in the program
◦ You must declare the variable with a name 
◦ “Assigning a value to a variable” means storing a value in it
◦ A variable may contain different values at different times while the program is running

Address Contents Variable names


0001 2 Num1
0002 3 Num2

0003 5 Sum

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 3

C# Variable naming convention
Rules:
◦ Declare a variable with data type and name

datatype variableName;

◦ Must begin with a letter or an underscore
◦ Can be followed by letters, underscore or digits.
◦ Case sensitive
◦ Cannot be a keyword
◦ Cannot have special characters (such as control chars, space) 

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 4
2017S2 ITP213

C# Keyword
A keyword is a word reserved by the C# compiler for its own use.  Below are C# keywords 
(list may change over time)
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
foreach goto if implicit in int interface
internal is lock long namespace new null
object operator out override params private protected
public readonly ref return sbyte sealed short
sizeof stackalloc static string struct switch this
throw true try typeof uint ulong unchecked
unsafe ushort using virtual void while

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 5

Categories of Types
Value types
◦ Built‐in primitive data types 
◦ E.g. int, float, double, decimal, bool, char, date etc

Reference types
◦ Reference type Variables store references to the actual data.
◦ Reference types are also referred to as objects.
◦ E.g. string, String,  all arrays, all class types such as Form
Pointer types
◦ Not in the scope of this module

6
ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 6
2017S2 ITP213

Common Value Types
C# Type Represent Range Example
bool Boolean value true or false bool isFound = “true”
byte 8‐bit unsigned integer 0 to 255 byte result = 246
char 16‐bit Single character U +0000 to U +ffff char status =‘A’
int 32‐bit signed integer type ‐2,147,483,648 to 2,147,483,647 int num1 = 156;
long 64‐bit signed integer type ‐9,223,372,036,854,775,808 to  long num2 =163245617;
9,223,372,036,854,775,807
short 16‐bit signed integer type ‐32,768 to 32,767 short num3 = 32767;
38 38
float 32‐bit single‐precision floating point  ‐3.4 x 10 to + 3.4 x 10 float price3 =80.0f
type
‐324 308
double 64‐bit double‐precision floating point  (+/‐)5.0 x 10 to (+/‐)1.7 x 10 double price2 = 109.8
type
28 28 0 to 28
decimal 128‐bit precise decimal values with 28‐ (‐7.9 x 10 to 7.9 x 10 ) / 10 decimal price = 2.95m
29 significant digits

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 7

Reference Types
String
◦ A sequence of characters enclosed by double quotes.
◦ string is an alias of String
◦ String myName = “Eevee”;
Use + operator to concatenate string variable
Example
string greeting = "Hello " + userName + ". Today is " + date + ".“

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 8
2017S2 ITP213

StringBuilder class
To optimise program performance, use StringBuilder to concatenate string.
String Builder is derived from System.Text class. 
Append and Appendline method concatenate multiple string variable into one string variable

Using System.Text; 
:
:

StringBuilder sqlcmd= new  StringBuilder();
sqlcmd.Appendline(“Select admNo, name, mobile,addr “);
sqlcmd.Appendline(“From Particular”);

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 9

Constants
Constant: contains information that does not change during the program 
execution
The naming rules are the same as those for variables
Use the const keyword before the data type when declaring a constant
Constants must be initialized in the declaration statement and cannot be 
changed later
Syntax
const type constantName = initialValue;
eg. const GST=0.07;

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 10
2017S2 ITP213

Data Type Conversion (string‐>numeric)
Web applications use string type in many places such as Text 
property of TextBox. Convert string to numeric to do arithmetic 
operation is required 
Two conversion methods
Parse method – convert string to required numeric data

Convert method  to convert one data type to another data type

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 11

Data Type Conversion (numeric‐>string)
Vice versus after the arithmetic operation in web application, it is 
required to assign the numeric variable into TextBox, hence 
converting numeric to string is needed
Two conversion methods
ToString method ToString does not handles a NULL value and a 
◦ tbQty.Text = stockQty.ToString()  NULL reference exception will occur

Convert.ToString method Convert.ToString is a safe method which 


◦ tbQty.Text =.Convert.ToString(stockQty) checks for null. It returns 
String.Empty when argument is null

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 12
2017S2 ITP213

Converting between Numeric Data Types
How to truncate
double to integer?

Two ways to convert numeric data type 
◦ Implicit
◦ Explicit(Casting)

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 13

Implicit Conversion
Conversion from a narrower data type to a wider data type

Example:  double bigNumberDouble = numberInteger;


From To
byte short, int, long, float, double, or decimal
short int, long, float, double, or decimal
int long, float, double, or decimal
long float, double, or decimal
float double

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 14
2017S2 ITP213

Explicit Conversion
Explicit conversion also known as casting
Casting is used to change a wider data to a narrower numeric data type  
Exception is generated if significant digits are lost when a cast is not 
performed
To cast, specify destination data type in parenthesis before value to 
convert

Examples:  
numberFloat = (float) numbeDecimal;
valueInteger = (int) valueDouble;

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 15

Circumstance of using Explicit Conversion
Given three integer variables A,B,C 
Given the statement derive average of the A,B,C

double _average =  A + B +C / 3;  returns 1
If A=2, B=2, C=1,  the result of _average = 1.666

double _average = (double) (A+B+C)/ 3; 

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 16
2017S2 ITP213

C# Operators
Arithmetic Operators – Binary Operators & Unary Operators
◦ Arithmetic operations are performed on data stored in numeric variables such as int and float.

Relational Operators
◦ Relational Operators are used to check whether a condition expression is true or false

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 17

C# Arithmetic Operations
Operator Operation
+ Addition

‐ Subtraction

* Multiplication

/ Division

% Modulus – Remainder of division

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 18
2017S2 ITP213

C# Arithmetic Operations Math class
C# Math class defines math methods

Method Description
Pow Returns the value number raised to the specified power. eg X 23
=>Math.Pow(X,23)
Round  Round value to specified number of decimal place eg. Rounded to 2 dec
=>Math.Round(X,2)
Sqrt Returns the square root of a specified number
=>Math.Sqrt(X)

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 19

Operator Precedence
Mathematic calculations have an “order of precedence”, 1 being the highest. If 2 
operations have the same order then the calculations occurs from left to right

Order of
precedence
() Left to Right 1
* /% Left to Right 2
+ - Left to Right 3
= Right to Left 4

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 20
2017S2 ITP213

C# Assignment  Operations
Operator Operation
= Assign value to a variable
Eg int count = 0; 
string hotLine=“6868999”;
+=     Perform a calculation and assign the result in one operation.
‐=  
*=  Eg
/=  totalSales += sales;
%=
is equivalent to 
totalSales = totalSales + Sales;

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 21

C# Unary Operators
Unary arithmetic operators 
◦ Are operators that require only  1 operand. 
◦ Unary operators include:
◦ Unary plus +
◦ Unary minus –
◦ Increment ++ and decrement operators ‐‐

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 22
2017S2 ITP213

C# Relation Operators
A condition is expressed using relational operators:

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 23

Program Flow Control  & Decision Making
The 3 basic structures that all computer programs commonly use:
1. Sequence
◦ Sequence control structure is the execution of one processing step after another. (ie. 
running commands line by line)
2. Selection
◦ Sometimes we need to take action based on some choice or decision.
eg. if mark is above 50 then student passes test, otherwise student fails test.
3. Repetition
◦ Perform certain instructions repeatedly, as long as a condition is true.
◦ Also called Looping or Iteration

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 24
2017S2 ITP213

Making Decisions Using if/else
The general form of if‐else implemented in C# is:
if (condition is true)
{
statement1;
statement2;
}
else
{ statement3;
statement4;
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 25

Making Decisions Using if/else
Read marks from a Textbox int iMarks = int.Parse(tbMarks.Text);
if (iMarks > 50 )
if marks > 50
{
Display “Pass” to Result Label lbResults.Text = “Pass”;
}
else else
{
Display “Fail” to Result Label
lbResults.Text = “Fail”;
}
end_if

Pseudo code C# code

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 26
2017S2 ITP213

Compound Boolean Expressions
Compound Boolean Expressions is used to test multiple conditions  
with logical operators && or ||.

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 27

AND Compound condition 
Condition 1 AND Condition 2
◦ BOTH Condition 1 and Condition 2 MUST be TRUE for the combined condition 
to be TRUE

Condition1 Condition2 1 AND 2

True True True


False True False
True False False
False False False

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 28
2017S2 ITP213

Making Decisions Using if/else
If it is raining AND it is wet, bring along an umbrella

bool cRain = true ;


boon cWet = true;
If ( (cRain == true) && (cWet == true))
lbMessage.Text =“Bring umbrella
as wet, rainy weather expected today.”;

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 29

OR Compound Condition
Condition 1 OR  Condition 2
◦ ONLY Condition 1 OR Condition 2 MUST be TRUE for the combined condition 
to be TRUE

Condition1 Condition2 1 OR 2

True True True


False True True
True False True
False False False

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 30
2017S2 ITP213

Making Decisions Using if/else
If you have a fever OR a headache, take panadol

bool cFever = false;


bool cHeadache = true;
if ( (cFever == true) || (cHeadache == true) )
lbMessage.Text = “Take panadol”;

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 31

Making Decisions Using if/else
Examine the following C# code:
int iAge, iDiscount=0;
char cWorking;
...................
If ((iAge > 55) && (cWorking == ‘N’ ))
iDiscount = 20;

iAge iAge > 55  cWorking cworking == ‘N’  Result iDiscount


condition condition
50 False ‘N’ True False 0
50 False ‘Y’ False False 0
60 True ‘N’ True True 20
60 True ‘Y’ False False 0

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 32
2017S2 ITP213

Making Decisions Using if/else
Examine the following C# code:
int iDiscount = 0;

if ((iAge > 55) ||(cWorking == ‘N’))


{
iDiscount = 20;
}

iAge Age > 55 cWorking cworking == ‘N’ Result iDiscount

50 False ‘N’ True True 20


50 False ‘Y’ False False 0

60 True ‘N’ True True 20


60 True ‘Y’ False True 20

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 33

Switch / Case
When if/else conditions become too complex, use switch‐case to make the code more readable.
switch (expression) Expression is a variable to be tested
{
case ConstantList: Constant list is the value used to match
Statement(s);
break; Break is required after each case to jumps out to the end of 
switch‐case
case ConstantList:
Statement(s); Execution of the statement body begins at the selected 
break; statement and proceeds until the break statement transfers 
control out of the case body
default:
Statement(s); If no case label contains a matching value, control is 
break; transferred to the default section
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 34
2017S2 ITP213

Switch/Case vs if/else
Example : Example :
if ( cardtype == 'A') {  switch (cardtype)
{
discount = 0.1; case 'A' :
} else if (cardtype = = 'B') {  discount = 0.1;
break;
discount = 0.15; case 'B' :
} else if (cardtype = = 'C') discount = 0.15;
break
.... //.....etc
.... case 'E' : 
discount = 0.2;
.... break;
} else if (cardtype = = 'E') {  default :
discount = 0;
discount = 0.25; break;
}
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 35

Sharing Conditions
char letter = (TextBoxLetter.Text);

switch (letter)
{ Two or more conditions can be shared
case ‘A’ :
case ‘a’ :
Response.Write(“A for apple”);
break;
case ‘B’ :
case ‘b’ :
Response.Write(“B for baby”);
break;
//.....etc
case ‘Z’ :
case ‘z’ : 
Response.Write(“Z for zoo”);
break;
default :
Response.Write(“Invalid Letter”);
break;
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 36
2017S2 ITP213

Methods
In most large software projects, thousands of lines of C# codes are written. If these codes were 
written as one single program, it would virtually be impossible to develop, debug, or test.
It is therefore, necessary to break down a complex problem to smaller simpler and manageable 
size of code block
Each algorithm is implemented as a module. In C#, these modules are known as methods.
A program causes the statements to be executed by calling the method and specifying any 
required method arguments

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 37

Structure of a Method
Method must be defined before using it.
return type: void means the 
MethodName has to follow Naming 
method is not returning any 
Conventions as variable name.
value to the calling program.

Access Modifier void MethodName( argument1, argument 2,…)


{ a pair of  round brackets 
a pair of braces or curly brackets denote the 
statement; method body containing C# statements
to contain 
arguments/parameters
statement;
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 38
2017S2 ITP213

Defining Methods
Access modifier: 
public ‐ class, method, variable or constructor declared public can be accessed from 
any other class.
private – method or constructor declared private can only be accessed within the 
declared class itself.
protected ‐ protected access allows a sub class to access the member variables and 
member functions of its base class.
https://www.youtube.com/watch?v=G238zPCJBu4
Internal                   
Not in the scope of this module
protected internal

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 39

Defining Methods
Return data type: indicates the type of data that the function will provide when 
it completes.
◦ void keyword: specifies that a function or method does not return a value
◦ Returned data type can be simple data type, struct or object 

Argument:  defines variables used within a method
◦ Placed within the parentheses of a method definition
◦ Must declare the data type of each argument
◦ Multiple parameters are separated by commas

Parameters are used like local variables within the body of the function

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 40
2017S2 ITP213

Calling a Method
A method is activated by calling its name together with 2 brackets ( ) that containing arguments
Example:
private void DisplayMenu( )
{
<…….. method body……>;
}
To call or activate the above method, we type:
DisplayMenu( );

This will pass the control to the DisplayMenu method.
When the DisplayMenu method finishes its job, the control will pass back to the place which called it.

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 41

Passing Data Between Methods
Type I Type II Type III Type IV

Parameters No Yes No Yes

Return Value No No Yes Yes

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 42
2017S2 ITP213

Type I :No Parameter And No Return
private void DisplayMenu( )
{
lbItem1.Tex = “1) Coffee” ;
lbItem2.Text = “2) Tea” ;
bItem3.Text = “3) Cake” ;
}
Calling the method

protected void Page_Load(object sender, EventArgs e)
{
DisplayMenue();
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 43

Type 2 : Has Parameter And No Return
public void showResult(double gpa) 
{ Access level – public
Return type  ‐ void
Method name – showResult
response.Write(“GPA : ” & gpa.tostring() );             Parameterlist ‐ GPA (double)
return;
}             
}
Calling the method
protected void btnclick (object sender, EventArgs e)
{  double studgpa = Convert.ToDouble(tbGPA.Text);
showResult(studgpa);
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 44
2017S2 ITP213

Type 3 : No Parameter But Has Return Data
public int gameLvl() 
Accesslevel – public
{ Return type  ‐ int
Method name – gameLvl
…..
Parameterlist ‐ empty
return 9;                                       

}
Calling the method

public int endgame ( )
{  
int score= gameLvl();
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 45

Type 4 : Has Parameter And Has Return
public double calArea(double width, double length) 
{ Access level – public
Return type  ‐ double
double area = width * length Method name – calArea
return area;                                        Parameterlist ‐ width(double)
length(double)
}
Calling the method

protected void btnclick (object sender, EventArgs e)
{  double rmwidth = Convert.ToDouble(tbWidth.Text);
double rmlen = Convert.ToDouble(tbLen.Text);
double area =calArea(rmwidth, rmlen); 
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 46
2017S2 ITP213

Let’s Practice
Write a method to compute area of square and return the area to call program. Assume the data 
type of the length of the square is integer type
Write the statement to call the above method where the length of square equal to 12.

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 47

Handling Exceptions
Processing with invalid input or failed methods can cause an exception to occur (also called 
throwing an exception)

“Catching” exceptions before they cause a run time error is called error trapping

Coding to take care of problems is called error handling

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 48
2017S2 ITP213

The try / catch Blocks
Enclose statement(s) that might cause an error in a try / catch block

If an exception occurs in try block, program control transfers to the catch block

Code in a finally statement is executed last

Specify type of exception to catch and program several catch statements

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 49

The try Block – General Form
try
{
// statements that may cause error
}
catch (ExceptionType VariableName)
{
// statements for action when exception occurs
}
finally
{// statements that always execute before exit of try block
}

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 50
2017S2 ITP213

Common Exception Type

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 51

Handling Multiple Exceptions
Include multiple catch blocks (handlers) to trap for more than one exception

catch statements are checked in sequence

The last catch can be coded to handle any exceptions not previously caught

A compiler warning is generated if a variable is declared but not used in a catch block

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 52
2017S2 ITP213

Best Practice for Exception handling
Handle errors by catching specific exceptions
int x;
lblmsg.text = string.Empty
try If txtBox_x is non numeric
{ x = int.Parse(txtBox_x.Text); }
catch (System.FormatException)
{  lblmsg.Text = "Please enter number"; }
catch (Exception err)
{ lblmsg.Text = ”please contact administrator";}
finally 
{ return; }

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 53

Summary
Various data types

Operator

Condition statement

Methods

Exception Handling

ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 54

You might also like