cn3 and 4 C
cn3 and 4 C
Handling
(Using Value Types)
Ch3 & 4
1
Objective
2
Content
3
Common Type System
• Overview of CTS
• Comparing Value and Reference Types
• Determining Base Types
• Comparing Built-in and User-Defined Value Types
• Simple Types
4
Overview of CTS
• CTS Supports Object-Oriented and Procedural Languages
• CTS Supports Both Value and Reference Type
Reference Types:
Value Types:
• Store references to their data
• Directly contain their data
(known as objects)
• Each has its own copy of data
• Two reference variables can
• Operations on one cannot
reference same object
affect another
• Operations on one can affect
another
5
Determining Base Types
• All Types Are Ultimately Derived from System.Object
• Value Types Are Derived from System.ValueType
• To Determine the Base Type of a Variable x, Use:
• x.GetType().BaseType
• Int num1;
• Console.WriteLine(num1.GetType().BaseType);
6
Comparing Built-in and User-Defined Value Types
Note: The only real difference between built-in data types and user-
defined data types is that you can write literal values for the built-in
types. 7
Simple Types
• Identified Through
Reserved Words
• int // Reserved keyword
• - or -
• System.Int32
8
Naming Variables
• Rules and Recommendations for Naming
Variables
• C# Keywords
• Quiz: Can You Spot Disallowed Variable
Names?
9
Rules and Recommendations for Naming Variables
• Rules
• Use letters, the underscore, and digits
• Start each variable name with a letter or underscore character.
• After the first character, use letters, digits, or the underscore
character
• Do not use reserved keywords.
• If you use a disallowed variable name, you will get a compile-time
error.
• Recommendations
• Avoid using all uppercase letters
• Avoid starting with an underscore
• Avoid using abbreviations
• Use PascalCasing naming in multiple-word names
10
C# Keywords
• Keywords Are Reserved
Identifiers
• Abstract, base, bool, default, if,
finally
• Do Not Use Keywords As
Variable Names
• Results in a compile-time error
• Avoid Using Keywords by
Changing Their Case Sensitivity
• int INT; //// Poor style
11
Quiz: Can You Spot the Disallowed Variable Names?
12
Quiz Answers
13
Using Built-in Data Types
14
Declaring Local Variables
• Usually Declared by Data Type and Variable Name:
• int itemCount;
• Possible to Declare Multiple Variables in One Declaration:
• int itemCount, employeeNumber;
• --or--
• int itemCount,
employeeNumber;
15
Assigning Values to Variables
16
Compound Assignment
• Adding a Value to a Variable Is Very Common
• itemCount = itemCount + 40;
• There Is a Convenient Shorthand
• itemCount + =40;
• This Shorthand Works for All Arithmetic Operators
• itemCount -= 24;
• Like:
• var += expression; // var = var + expression
• var -= expression; // var = var - expression
• var *= expression; // var = var * expression
• var /= expression; // var = var / expression
• var %= expression; // var = var % expression
17
Common Operators
• Common Operators Examples
• Equality operators == !=
• Relational operators < > <= >= is
• Conditional operators && || ?:
• Increment operator ++
• Decrement operator --
• Arithmetic operators +-*/%
• Assignment operators = *= /= %= += -= <<=
>>= &= ^= |=
18
Increment and Decrement
• Changing a Value by One Is Very Common
itemCount += 1;
itemCount -= 1;
• There Is a Convenient Shorthand
itemCount++;
itemCount--;
• This Shorthand Exists in Two Forms
++itemCount;
--itemCount;
19
Operator Precedence
• Operator Precedence and Associativity
• Except for assignment operators, all binary operators are left-
associative
• Assignment operators and conditional operators are right-
associative
• x + y + z is evaluated as (x + y) + z.
• This is particularly important for assignment operators.
• For example, x = y = z is evaluated as x = (y = z).
• You can control precedence and associativity by using parentheses.
• For example, x + y * z first multiplies y by z and then adds the result to x, but
(x + y) * z first adds x and y and then multiplies the result by z
20
Creating User-Defined Data Types
• Enumeration Types
• Structure Types
21
Enumeration Types
• Defining an Enumeration Type Color colorPalette;
colorPalette = Color.Red;
// Declare the variable
// Set value
• enum Color { Red, Green, Blue } - Or -
colorPalette = (Color)0; // Type casting int to Color
24
Implicit Data Type Conversion
• To Convert Int to Long:
using System;
class Test
{
static void Main( )
{
int intValue = 123;
long longValue = intValue;
Console.WriteLine("(long) {0} = {1}", intValue,longValue);
}
}
• Implicit Conversions Cannot Fail
• May lose precision, but not magnitude
25
Explicit Data Type Conversion
• To Do Explicit Conversions, Use a Cast Expression:
using System;
class Test
{
static void Main( )
{
long longValue = Int64.MaxValue;
int intValue = (int) longValue;
Console.WriteLine("(int) {0} = {1}", longValue, intValue);
}
}
26
Ch4
Statements
and
Exceptions 27
Overview
• Introduction to Statements
• Using Selection Statements
• Using Iteration Statements
• Using Jump Statements
• Handling Basic Exceptions
• Raising Exceptions
28
Introduction to Statements
•Statement Blocks
•Types of Statements
29
Statement Blocks
{
• Use Braces As Block Delimiters // code
}
{
int i;
...
{
int i;
{
• A Block and Its Parent Block Cannot Have a Variable ... int i;
with the Same Name } ...
} }
...
{
int i;
• Sibling Blocks Can Have Variables with the Same ...
Name
} 30
Types of Statements
• Selection Statements
• The if and switch statements
• Iteration Statements
• The while, do, for, and foreach statements
• Jump Statements
• The goto, break, and continue statements
31
Using Selection Statements
• The if Statement
• Cascading if Statements
• The switch Statement
• Quiz: Spot the Bugs
32
The if Statement
if (number % 2 == 0)
{
• Syntax: Console.WriteLine("even");
}
if ( Boolean-expression ) else
first-embedded-statement {
else Console.WriteLine(“Odd");
}
second-embedded-statement
• No Implicit Conversion from int to bool
int x;
...
if (x) ... // Must be if (x != 0) in C#
if (x = 0) ... // Must be if (x == 0) in C#
33
Cascading if Statements Exercise
Console.Write("Enter first number: ");
1. Write a C# program that can
int firstNumber = int.Parse(Console.ReadLine());
Console.Write("Enter second number: "); generate Grade based on users mark
int secondNumber = int.Parse(Console.ReadLine()); input of test1(15%), test1(15%),
int biggerNumber = firstNumber; Mid(25%), Final(45%), and the
if (secondNumber > firstNumber) following scale:
{ biggerNumber = secondNumber; • Above 90 is A, Above 75 B,
Console.WriteLine("bigger is: {0}", biggerNumber);}
else if(secondNumber < firstNumber)
Above 50 C, and Above 40 D. if
{ biggerNumber = firstNumber; not F
Console.WriteLine(“bigger is: {0}", biggerNumber); }
else 2. Write a C# program that can inform
{ Console.WriteLine("both number are equal");} your age group as kid, youth, adult
or old age based on your age input.
34
The switch Statement • Write a simple application that
can accept two numbers and
• Use switch Statements for Multiple Case Blocks
provide either the product,
• Use break Statements to Ensure That No Fall Through Occurs
summation, difference, or quotient
Console.Write("Enter week day in Number: ");
based on the user selection of:
int weekday = int.Parse(Console.ReadLine());
switch (weekday) • +, -, /, and *
{ case 1: Console.WriteLine("Monday"); break;
• If the user inputs any other
case 2: Console.WriteLine("Tueasday"); break;
case 3: Console.WriteLine("Wednsday"); break;
character the program
case 4: Console.WriteLine("Thursday"); break;
should stay until either of
case 5: Console.WriteLine("Friday"); break; them is submitted.
case 6: case 7: Console.WriteLine("Week Ends"); break;
default: Console.WriteLine("Not Week Days"); break;
}
Console.ReadLine();
35
Quiz: Spot the Bugs
36
Answers
• 1. The if statement is not in parentheses. The C# compiler traps this bug as a compile-time error. The corrected
code is as follows:
• if (number % 2 == 0) ...
• 2. The if statement as a whole is not fully parenthesized. The C# compiler traps this bug as a compile-time
error. The corrected code is as follows:
• if ((percent < 0) | (percent > 100)) ...
• 3. The if statement has a single semicolon as its embedded statement. A single semicolon is called an empty
statement in the C# Language Reference document and a null statement in the C# compiler diagnostic
messages. It does nothing, but it is allowed. The layout of the statements does not affect how the compiler
parses the syntax of the code. Hence, the compiler reads the code as:
• if (minute == 60)
• ;
• minute = 0;
• The C# compiler traps this bug as a compile-time warning.
• 4. The following errors are present:
• a. There is more than one constant in the same case label. The C# compiler traps this bug as a compile-time error.
• b. The statements associated with each case fall through to the next case. The C# compiler traps this bug as a compile-time
error.
• c. The keyword default has been misspelled. Unfortunately, this is still allowable code, as it creates a simple identifier label.
The C# compiler traps this bug as two compile-time warnings: one indicating unreachable code, and another indicating that
the default: label has not been used.
37
Using Iteration Statements
38
The while Statement
• Execute Embedded Statements Based on Boolean Value
• Evaluate Boolean Expression at Beginning of Loop
• Execute Embedded Statements While Boolean Value Is True
int i = 0;
while (i < 10)
{ 0
1 initializer
Console.WriteLine(i); 2 while ( Boolean-expression )
i++; 3 {
4 embedded-statement
} 5 update
6 }
7
8
9
39
The do Statement
• Execute Embedded Statements Based on Boolean Value
• Evaluate Boolean Expression at End of Loop
• Execute Embedded Statements While Boolean Value Is
True
• int i = 0;
int num1, num2;
• do do
• { {
Console.WriteLine("enter number 1");
• Console.Write(i); num1 = int.Parse(Console.ReadLine());
• i++; Console.WriteLine("enter number 1");
num2 = int.Parse(Console.ReadLine());
• } while (i < 10); if (num1>10 && num2>10) {
•0123456789 Console.WriteLine("the numbers are {0}, {1}" , num1, num2);
}
else {
Console.WriteLine("write two numbers each greater than 10");
}
} while (num1<10 || num2<10);
40
for ( initializer ; condition ; update )
The for Statement {
embedded-statement
}
• Place Update Information at the Start of
the Loop
for (int i = 0; i < 10; i++)
{ int num1, num2;
Console.WriteLine(i); Console.Write("enter row");
} num1 = int.Parse(Console.ReadLine());
Console.Write("enter column");
• Variables in a for Block are Scoped Only num2 = int.Parse(Console.ReadLine());
Within the Block for (int i=1; i<=num1; i++)
for (int i = 0; i < 10; i++) {
Console.WriteLine(i); for (int j = num2; j >=1; j--)
Console.WriteLine(i); // Error: i is no longer in {
scope
if (j >= i) {Console.Write(" ");}
• A for Loop Can Iterate Over Several Values else {Console.Write(j);}
• for (int i= 0, j= 0; ... ; i++, j++) }
Console.WriteLine();
}
41
The foreach Statement
• Choose the Type and Name of the Iteration Variable
. . . • Execute Embedded Statements for Each Element of the Collection Class
using System.Collections;
namespace ConsoleApplication17 Using System.Collection;
...
{
ArrayList numbers = new ArrayList( );
class Program for (int i = 0; i < 10; i++)
{ {
static void Main(string[] args) numbers.Add(i);
{ }
ArrayList numbers = new ArrayList();
for (int i = 0; i < numbers.Count; i++)
for (int i = 0; i < 10; i++) {
{ numbers.Add(i); } int number = (int)numbers[i];
foreach (int number in numbers) Console.WriteLine(number);
{ Console.WriteLine(number); } }
}}}
42
0123456789
Quiz: Spot the Bugs
43
Answers
• 1. The for statement elements are separated by commas rather than semicolons. The C# compiler traps this bug
as a compile-time error. The corrected code is as follows:
• for (int i = 0; i < 10; i++)
• ...
• 2. The while statement does not update the continuation expression. It will loop forever. This bug does not
generate a warning or an error at compile time. The corrected code is as follows:
• int i = 0;
• while (i < 10) {
• Console.WriteLine(i);
• i++;
• }
• 3. The for statement has a termination rather than a continuation condition. It will never loop at all. This bug
does not generate a warning or an error at compile time. The corrected code is as follows:
• for (int i = 0; i < 10; i++)
• ...
• 4. The statements between do and while must be grouped together in a block. The C# compiler traps this bug as
a compile-time error. The corrected code is as follows:
• do {
• ...
• string s = Console.ReadLine( );
• guess = int.Parse(s);
• } while (guess != answer);
44
Using Jump Statements
45
The goto Statement
• Flow of Control Transferred to a Labeled Statement
int number;
Console.WriteLine("Enter Number");
Even:
number = int.Parse(Console.ReadLine());
{
if (number % 2 == 0)
for( int i=1; i<=number; i++)
goto Even;
if (i%2==0) { Console.Write(i); }
else }
goto Odd; Odd:
{
Console.WriteLine("Enter Number"); for (int i = 1; i <= number; i++)
int num2, num1 = int.Parse(Console.ReadLine()); if (i % 2 != 0) { Console.Write(i);}
num2 = num1 * num1; }
Console.WriteLine(num2);
46
The break and continue Statements
int num1;
• The break Statement Jumps out of an Console.WriteLine("Enter Maximum Number");
Iteration num1 = int.Parse(Console.ReadLine ());
• The continue Statement Jumps to the for (int i = 1; i <= num1; i++)
Next Iteration {
int i = 0; if (i % 2 != 0)
while (true) {
{ Console.Write(", " + i);
Console.WriteLine(i); }
i++; else if(i==8)
if (i < 10) {
continue; break;
else }
break; else
} {
continue;
}
} 47
Handling Basic Exceptions
• Why Use Exceptions?
• Exception Objects
• Using try and catch Blocks
48
Why Use Exceptions?
• Traditional Procedural Error Handling Is Cumbersome
49
Exception Objects
50
Using try and catch Blocks
• Object-Oriented Solution to Error Handling
• Put the normal code in a try block
• Handle the exceptions in a separate catch block
51
Multiple catch Blocks
• Each catch Block Catches One Class of try {
Exception int number;
Console.WriteLine("Enter Number");
• A try Block Can Have One General Catch number = int.Parse(Console.ReadLine());
Block if (number % 2 == 0) goto Even;
Else goto Odd;
• A try Block Is Not Allowed to Catch a Class Even:
That Is Derived from a Class Caught in an {
for (int i = 1; i <= number; i++)
Earlier catch Block if (i % 2 == 0) {Console.Write(i); }
try { }
File source = new File("code.cs"); Odd:
{
int length = (int)source.Length; for (int i = 1; i <= number; i++)
char[ ] contents = new char[length]; if (i % 2 != 0){Console.Write(i); }
... }
}
} catch (System.Exception caught)
catch (SecurityException caught) { ... } {
Console.WriteLine("Here is error: {0}", caught);
catch (IOException caught) { ... } }
catch (OutOfMemoryException caught) { ... }
52
Methods and Parameters
• Using Methods
• Using Parameters
53
Using Methods
• Defining Methods
• Calling Methods
• Using the return Statement
• Using Local Variables
• Returning Values
54
Defining Methods
• Main Is a Method
• Use the same syntax for defining your own methods
• A method is group of C# statements that have been brought together and given a
name. Most modern programming languages have a similar concept; you can
think of a method as being like a function, a subroutine, a procedure or a
subprogram.
using System;
• Examples of Methods class ExampleClass
• The code on the slide contains three methods: {
static void ExampleMethod( )
• The Main method {
• is the entry point of the application. Console.WriteLine("Example method");
• The WriteLine method: }
static void Main( )
• static method of the class System.Console {
• The ExampleMethod method // ...
• ExampleMethod method belongs to ExampleClass }
55
}
Creating Methods
In C#, all methods belong to a class. This is unlike programming languages such as C,
C++, and Microsoft Visual Basic which allow global subroutines and functions.
• When creating a method, you must specify the following:
• Name
• You cannot give a method the same name as a variable, a constant, or any other non-
method item declared in the class. The method name can be any allowable C# identifier,
and it is case sensitive.
• Parameter list
• The method name is followed by a parameter list for the method. This is enclosed between
parentheses. The parentheses must be supplied even if there are no parameters, as is shown
in the examples on the slide. static void MethodName ( )
{
• Body of the method method body
}
• Following the parentheses is the body of the method. You must enclose the method body
within braces ({ and }), even if there is only one statement.
56
Calling Methods
•After You Define a Method, You Can: MethodName( );
} 58
Calling Methods from Other Classes
• To allow methods in one class to using System;
call methods in another class, you class A
must: {
public static void TestMethod( )
• Specify which class contains the {
Console.WriteLine("This is TestMethod in class A");
method you want to call. }
• To specify which class contains the }
method, use the following syntax: class B
• ClassName.MethodName( ); {
static void Main( )
• Declare the method that is called {
A.TestMethod( );
with the public keyword. }
• The following example shows how to }
63
Using Local Variables
• Local Variables
• You can include local variables in the body of a method, as shown in the
• following example:
static void MethodWithLocals( )
{
int x = 1; // Variable with initial value
ulong y;
string z;
}
64
Shared Variables class CallCounter_Bad
{
• Consider the following code, which static void Init( )
attempts to count the number of {
int nCount = 0;//not used or called
times a method has been called: }
• This program cannot be static void CountCalls( )
compiled because of two {
important problems. int nCount; //no value assigned
++nCount;
• The variable nCount in Init is Console.WriteLine("Method called {0}
not the same as the variable time(s)", nCount);
nCount in CountCalls. }
• In C#, you can declare a local variable that static void Method1()
has the same name as a class variable, but {
int numItems = 42;
this can produce unexpected results. In the Console.WriteLine(numItems);
following example, NumItems is declared as a }
variable of class ScopeDemo, and also static void Method2()
declared as a local variable in Method1. {
numItems = 61;
• The two variables are completely different. Console.WriteLine(numItems);
• In Method1, numItems refers to the local variable. }
• In Method2, numItems refers to the class static void Main()
variable. {
Method2();
Method1();
Console.WriteLine(numItems);
}
}
67
Return with a Value
• If a method is defined with a data type rather
than void, the return mechanism is used to
assign a value to the function.
• Declare the Method with Non-Void Type
• Add a return Statement with an Expression
• Sets the return value
• Returns to caller
• Non-void Methods Must Return a Value int x;
x = TwoPlusTwo( );
static int TwoPlusTwo( ) Console.WriteLine(x);
{
int a,b;
a = 2;
b = 2;
return a + b;
} 68
Return with a Value class ExampleReturningValue
{
• The following example shows static int TwoPlusTwo( )
{
how to declare a method int a,b;
named TwoPlusTwo that will a = 2;
return a value of 4 to Main b = 3;
when TwoPlusTwo is called: return a + b;
}
70
Declaring and Calling Parameters
• Declaring Parameters
• Place between parentheses after method name
• Define type and name for each parameter
• Calling Methods with Parameters
• Supply a value for each parameter
static void MethodWithParameters(int n, string y)
{ ... }
MethodWithParameters(2, "Hello, world");
• Declaring Parameters
• The following example shows how to declare a static void MethodWithParameters(int n, string y)
{
method with parameters: // ...
}
73
Pass by Reference
• What Are Reference Parameters?
• A reference to memory location
• Using Reference Parameters
• Use the ref keyword in method declaration and call
• Match types and variable values
• Changes made in the method affect the caller
• Assign parameter value before calling the method
static void ShowReference(ref int nVar, ref long nCount)
{
// ...
}
75
Pass by Reference
• Assigning Parameters Before Calling the static void AddOne(ref int x)
{
Method x++;
• A ref parameter must be definitively assigned }
at the point of call; that is, the compiler must static void Main( )
ensure that a value is assigned before the call {
is made. The following example shows how int k = 6;
you can initialize reference parameters before AddOne(ref k);
calling the method: Console.WriteLine(k); // 7
}
• The following example shows what
happens if a reference parameter k is not
initialized before its method AddOne is
called: int k;
• The C# compiler will reject this code and AddOne(ref k);
Console.WriteLine(k);
display the following error message: “Use
of unassigned local variable ‘k.’”
76
Guidelines for Passing Parameters
namespace Swapp_Text
• Mechanisms {
• Pass by value is most common private void button6_Click(object sender, EventArgs e)
{
• Method return value is useful for string a, b;
a = "Hale";
single values b = "Luya";
• Use ref and/or out for multiple swapptext( ref a, ref b);
return values textBox4.Text = a;
textBox5.Text = b;
• Only use ref if data is transferred }
both ways private void swapptext( ref string j, ref string h)
• Efficiency {
j=textBox4.Text ;
• Pass by value is generally the most h=textBox5.Text;
string temp = j;
efficient j= h;
h = temp;
}
}
77
Using Recursive Methods
• A Method Can Call Itself
• Directly
• Indirectly
• Useful for Solving Certain Problems
• Example
• You can implement the Fibonacci method as follows:
static ulong Fibonacci(ulong n)
{
if (n <= 2)
return 1;
else
return Fibonacci(n-1) + Fibonacci(n-2);
}
• A recursive method must have a terminating condition that ensures that it will
return without making further calls. In the case of the Fibonacci method, the test
for n <= 2 is the terminating condition. 78
Exercise
• According to the interface give:
1. Write four methods for athematic
operation and call them through a
button click for each to show the result
on message box
2. Write a method that can check if a
given letter is a vowel or not? And call
the method through a click event to
show the result on message box
3. Write a method that can take two
names and swap them. For both:
1. Use calling by value
2. Use call by reference
79