0% found this document useful (0 votes)
51 views79 pages

cn3 and 4 C

The document discusses object-oriented fundamentals and exception handling using value types in C#, including describing variable types, naming conventions, declaring variables with built-in data types, assigning values, converting data types, creating user-defined data types like enumerations and structures, and handling exceptions. It covers topics like the common type system, built-in versus user-defined value types, and using operators, variables, and data types in C# code examples.

Uploaded by

yeshi janexo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views79 pages

cn3 and 4 C

The document discusses object-oriented fundamentals and exception handling using value types in C#, including describing variable types, naming conventions, declaring variables with built-in data types, assigning values, converting data types, creating user-defined data types like enumerations and structures, and handling exceptions. It covers topics like the common type system, built-in versus user-defined value types, and using operators, variables, and data types in C# code examples.

Uploaded by

yeshi janexo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

OO Fundamentals and Exception

Handling
(Using Value Types)
Ch3 & 4

1
Objective

• After completing this module, you will be able to:


• Describe the types of variables that you can use in C# applications.
• Name your variables according to standard C# naming conventions.
• Declare a variable by using built-in data types.
• Assign values to variables.
• Convert existing variables from one data type to another.
• Create and use your own data types.

2
Content

• Common Type System


• Naming Variables
• Using Built-in Data Types
• Creating User-Defined Data Types
int Num1;
• Converting Data Types int Num2;
int result = 0;
private void button1_Click(object sender, EventArgs e)
{
Num1 = Convert.ToInt32(textBox1.Text);
Num2 = Convert.ToInt32(textBox2.Text);
result = Num1 + Num2;
textBox3.Text =Convert.ToString(result);
}

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

• Examples of Built-in Value • Examples of User-Defined Value


Types: Types:
• int • enum
• float • struct

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

1. Disallowed. Variable names cannot begin with a digit.


2. Disallowed. Variable names must start with a letter or an
underscore.
3. Allowed. Variable names can start with a letter.
4. Disallowed. Keywords (this) cannot be used to name variables.
5. Allowed. Variable names can start with an underscore.

13
Using Built-in Data Types

• Declaring Local Variables


• Assigning Values to Variables
• Compound Assignment
• Common Operators
• Increment and Decrement
• Operator Precedence

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

• Assign Values to Variables That Are Already Declared:


int employeeNumber;
employeeNumber = 23;
• Initialize a Variable When You Declare It:
int employeeNumber = 23;
• You Can Also Initialize Character Values:
char middleInitial == ''J'';;

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

• Using an Enumeration Type


• Color colorPalette = Color.Red; Console.WriteLine(“{0}”,colorPalette);

• Displaying an Enumeration Variable Console.WriteLine(“{0}”,colorPalette); //


Displays Red
enum color { Red, Green, Blue }
static void Main(string[] args)
{
color colorss = color.Blue;
Console.WriteLine ("this is {0} color", colorss);
Console.WriteLine(colorss);
} 22
public struct student
Structure Types {
public string sname,ssex,sid;
public int age;
• Defining a Structure Type private char sgrade;
}
public struct Employee static void Main(string[] args)
{
{ student s1,s2;
string firstName; s1.sname = "Fekadey"; s1.age = 45; s1.ssex = "Male";
s1.sid = "GSS/101/07";
int age; // s1.sgrade= " A";
}
s2.sname = "Selamawit"; s2.age = 45; s2.ssex = "Female";
• Using a Structure Type s2.sid = "GSS/101/07";

Employee companyEmployee; Console.WriteLine ("Student 1 is :\n Name :{0} \n Sex


:{1} \n IDNO :{2} \n Age :{3}", s1.sname,
companyEmployee.firstName = "Joe"; s1.ssex,s1.sid,s1.age);
companyEmployee.age = 23; Console.WriteLine("Student 2 is :\n Name :{0} \n Sex
:{1} \n IDNO :{2} \n Age :{3}", s2.sname, s2.ssex,
s2.sid, s2.age);
}
In this example the student grade is not accessible
This is because it is private to the struct 23
Converting Data Types
• Implicit Data Type Conversion
• Explicit Data Type Conversion

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

•The while Statement


•The do Statement
•The for Statement
•The foreach Statement
•Quiz: Spot the Bugs

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

• The goto Statement


• The break and continue 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( );

• Call a method from within the same class


• Use method’s name followed by a parameter list in parentheses
• Call a method that is in a different class
• You must indicate to the compiler which class contains the
method to call.
• The called method must be declared with the public keyword
• Use nested calls
• Methods can call methods, which can call other methods, and so
on
57
using System;
Calling Methods class ExampleClass
{
• To call a method, use the name
of the method followed by a static void ExampleMethod( )
parameter list in parentheses. {
The parentheses are required Console.WriteLine("Hello, world");
even if the method that you call }
has no parameters, as shown in
the following example. static void Main( )
{
Console.WriteLine("The program is starting");
MethodName( ); ExampleMethod( );
Console.WriteLine("The program is ending");
}

} 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 }

call the method TestMethod, which is


defined in class A, from Main in class
B: 59
namespace ConsoleApp2
{ class product
class Program {
{ public static void pproduct()
static void Main(string[] args) {
{ int num1 = 4, num2 = 3, result;
add.aadd(); result = num1 * num2;
product.pproduct(); Console.WriteLine("Product {0}", result);
division.ddivision(); }
} }
//Console.ReadLine(); class division
} {
class add public static void ddivision()
{ {
public static void aadd() int num1 = 4, num2 = 3, result;
{ result = num1 / num2;
int num1 = 4, num2 = 3, result; Console.WriteLine("Division {0}", result);
result = num1 + num2; }
Console.WriteLine("Addition {0}" ,result); }
} }
}
60
Nesting Method Calls
using System;
• You can also call methods from class NestExample
within methods. {
static void Method1()
• The following example shows how to {
nest method calls: Console.WriteLine("ICT 3rd");
}
static void Method2()
{
Method1();
The output from this program is as Console.WriteLine("ICT 2nd");
follows: Method1();
}
static void Main()
{
Method2();
Method1();
}
}
61
Using the return Statement static void ExampleMethod( )
• Immediate Return {
int numBeans;
• Return with a Conditional Statement
//...
• You can use the return statement to make a
method return immediately to the caller. Console.WriteLine("Hello");
• Without a return statement, execution usually if (numBeans < 10)
returns to the caller when the last statement in the return;
method is reached.
Console.WriteLine("World");
• Immediate Return }
• By default, a method returns to its caller when the
end of the last statement in the code block is class NestExample
reached. If you want a method to return {
immediately to the caller, use the return statement. static void Main()
• In the following example, the method will display { ExampleMethod(); }
“Hello,” and then immediately return to its caller: static void ExampleMethod()
{ Console.WriteLine("Hello");
• Using the return statement like this is not very
return;
useful because the final call to Console.WriteLine is
never executed Console.WriteLine("World");
}
} 62
Using Local Variables
• Local Variables
• Created when method begins
• Private to the method
• Destroyed on exit
• Shared Variables
• Class variables are used for sharing
• Scope Conflicts
• Compiler will not warn if local and class names clash
• Each method has its own set of local variables. You can use these variables only
inside the method in which they are declared. Local variables are not accessible
from elsewhere in the application.

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. }

• No matter how many times you static void Main( )


call the method CountCalls, the {
value nCount is lost each time Init( );
CountCalls( );
CountCalls finishes. CountCalls( );
}
} 65
Shared Variables class CallCounter_Good
{
static int nCount;
• The correct way to write static void Init( )
{
this code is to use a class nCount = 0;
variable, as shown in the }

following example: static void CountCalls( )


{
• In this example, nCount is ++nCount;
declared at the class level Console.Write("Method called " + nCount +
" time(s).");
rather than at the method }
level. static void Main( )
• Therefore, nCount is shared {
Init( );
between all of the methods CountCalls( );
CountCalls( );
in the class. }
}
66
class ScopeDemo
Scope Conflicts {
static int numItems = 0;

• 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;
}

static void Main( )


{
int x=9;
x = TwoPlusTwo( );
Console.WriteLine(x);
}
} 69
Using Parameters
• Declaring and Calling Parameters
• Mechanisms for Passing Parameters
• Pass by Value
• Pass by Reference
• Guidelines for Passing Parameters
• Using Recursive Methods

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: // ...
}

• This example declares the MethodWithParameters method with two parameters:


n and y. The first parameter is of type int, and the second is of type string. 71
Mechanisms for Passing Parameters
• Three Ways to Pass Parameters:
• In: Passing by Value
• In out: Passing by Reference
• Out: Output Parameters
• Parameters can be passed in three different ways:
• By value
• Value parameters are sometimes called in parameters because data can be transferred into the method
but cannot be transferred out.
• By reference
• Reference parameters are sometimes called in/out parameters because data can be transfer red into the
method and out again.
• By output
• Output parameters are sometimes called out parameters because data can be transferred out of the
method but cannot be transferred in.
72
Pass by Value class CallbyValue
{
• Default Mechanism For static void AddOne(int x)
Passing Parameters: {
• Parameter value is copied x += 10;
x++; // Increment x
• Variable can be changed inside Console.WriteLine(x);
the method }
• Has no effect on value outside
the method static void Main()
• Parameter must be of the {
same type or compatible type int k = 6;
AddOne(k);
Console.WriteLine(k); // Display the value 6, not 17
}
}

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)
{
// ...
}

static void OneRefOneVal(ref int refVar, long longVar)


{
// ...
} 74
int x;
Pass by Reference long q;
ShowReference(ref x, ref q);
• Matching Parameter Types and Values
• When calling the method, you supply class CallbyRef
reference parameters by using the ref {
static void AddOne(ref int x)
keyword followed by a variable. The value {
supplied in the call to the method must x += 10;
exactly match the type in the method x++; // Increment x
definition, and it must be a variable, not a Console.WriteLine(x);
constant or calculated expression. }

• Changing Reference Parameter Values static void Main()


{
• If you change the value of a reference int k = 6;
parameter, the variable supplied by the caller AddOne(ref k);
is also changed, because they are both Console.WriteLine(k); // Display the value 6, not 7
references to the same location in memory. }

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

You might also like