SlideShare a Scribd company logo
Visual Programming
Methods, Classes, and Objects
Classes/Methods
C# Framework Class Library (FCL) defines many classes, e.g.,
Console
MessageBox
Int32
Math

The definition of a class includes both methods and data
properties:
methods, e.g.,

• Console.Write( )
• Console.WriteLine( )
• Int32.Parse( )

properties, e.g.,
•
•
•
•

Int32.MinValue
Int32.MaxValue
Math.PI
Math.E
2
Methods
A method should provide a well-defined, easy-tounderstand functionality

A method takes input (parameters), performs some actions,
and (sometime) returns a value

Example: invoking the WriteLine method of the
Console class:
Console.WriteLine ( "Whatever you are, be a good one.“ );
method

class
dot

Information provided to the method
(parameters)

3
Example: Math Class Methods
Method
Abs( x )

Description
absolute value of x

Ceiling( x ) rounds x to the smallest
integer not less than x
Cos( x )
trigonometric cosine of x
(x in radians)
Exp( x )
exponential method ex

Floor( x )
Log( x )

Max( x, y )

Min( x, y )

Pow( x, y )
Sin( x )
Sqrt( x )
Tan( x )

Example
Abs( 23.7 ) is 23.7
Abs( 0 ) is 0
Abs( -23.7 ) is 23.7
Ceiling( 9.2 ) is 10.0
Ceiling( -9.8 ) is -9.0
Cos( 0.0 ) is 1.0

Exp( 1.0 ) is approximately
2.7182818284590451
Exp( 2.0 ) is approximately
7.3890560989306504
rounds x to the largest integer Floor( 9.2 ) is 9.0
not greater than x
Floor( -9.8 ) is -10.0
natural logarithm of x (base e) Log( 2.7182818284590451 )
is approximately 1.0
Log( 7.3890560989306504 )
is approximately 2.0
larger value of x and y
Max( 2.3, 12.7 ) is 12.7
(also has versions for float, Max( -2.3, -12.7 ) is -2.3
int and long values)
smaller value of x and y
Min( 2.3, 12.7 ) is 2.3
(also has versions for float, Min( -2.3, -12.7 ) is -12.7
int and long values)
x raised to power y (xy)
Pow( 2.0, 7.0 ) is 128.0
Pow( 9.0, .5 ) is 3.0
trigonometric sine of x
Sin( 0.0 ) is 0.0
(x in radians)
square root of x
Sqrt( 900.0 ) is 30.0
Sqrt( 9.0 ) is 3.0
trigonometric tangent of x
Tan( 0.0 ) is 0.0
(x in radians)

Commonly used Math class methods.

4
Methods Provide Abstraction and Reuse
An abstraction hides (or ignores) the right
details at the right time
A method is abstract in that we don't really
have to think about its internal details in order
to use it
e.g., we don't have to know how the WriteLine
method works in order to invoke it

Why abstraction?

Divide and conquer
Reuse
Easier to understand
5
Method Declaration: Header
A method declaration begins with a method header
class MyClass
{ …
static int

SquareSum( int num1, int num2 )

parameter list
method
name
The parameter list specifies the type
and name of each parameter
return
type
The name of a parameter in the method
properties
declaration is called a formal argument
6
Method Declaration: Body
The method header is followed by the method body
class MyClass
{
…
static int SquareSum(int num1, int num2)
{
int sum = num1 + num2;
return sum * sum;
}
…
}

7
The return Statement
The return type of a method indicates the
type of value that the method sends back to
the calling location
A method that does not return a value has a
void return type
The return statement specifies the value that
will be returned
Its expression must conform to the return
type
8
Calling a Method
Each time a method is called, the actual arguments in
the invocation are copied into the formal arguments
int

num = SquareSum (2, 3);

static int SquareSum (int num1, int num2)
{
int sum = num1 + num2;
return sum * sum;
}

9
Class Methods (a.k.a. Static Methods)
Previously we use class mainly to define
related methods together:

For example all math related methods are defined in
the Math class

The methods we have seen are defined as
static (or class) methods
To make a method static, a programmer
applies the static modifier to the method
definition

The result of each invocation of a class (static) method is
completely determined by the actual parameters
10
Method Overloading
The following lines use the WriteLine method for different
data types:
Console.WriteLine ("The total is:");
double total = 0;
Console.WriteLine (total);

Method overloading is the process of using the same
method name for multiple methods
Usually perform the same task on different data types

Example: The WriteLine method is overloaded:
WriteLine (String s)
WriteLine (int i)
WriteLine (double d)

…

11
Method Overloading: Signature
The compiler must be able to determine
which version of the method is being invoked
This is by analyzing the parameters, which
form the signature of a method
The signature includes the number, type, and
order of the parameters
The return type of the method is not part of the
signature

12
Method Overloading
Version 1

Version 2

double TryMe (int x)
{
return x + .375;
}

double TryMe (int x, double y)
{
return x*y;
}

Invocation
result = TryMe (25, 4.32)

13
Parameters: Modifying Formal Arguments
You can use the formal arguments (parameters) as
variables inside the method
Question: If a formal argument is modified inside a
method, will the actual argument be changed?
static int Square ( int x )
{
x = x * x;
return x;
}
static void Main ( string[] args )
{
int x = 8;
int y = Square( x );
Console.WriteLine ( x );
}

14
Parameter Passing
If a modification on the formal argument has no
effect on the actual argument,
it is call by value

If a modification on the formal argument can
change the actual argument,
it is call by reference

15
Call-By-Value and Call-By-Reference in C#
Depend on the type of the formal argument
For the simple data types, it is call-by-value
Change to call-by-reference

The ref keyword and the out keyword change a
parameter to call-by-reference

• If a formal argument is modified in a method, the value is
changed
• The ref or out keyword is required in both method
declaration and method call
• ref requires that the parameter be initialized before
enter a method while out requires that the parameter be
set before return from a method

16
Example: ref
static void Foo( int p ) {++p;}
static void Main ( string[] args )
{
int x = 8;
Foo( x ); // a copy of x is made
Console.WriteLine( x );
}
static void Foo( ref int p ) {++p;}
static void Main ( string[] args )
{
int x = 8;
Foo( ref x ); // x is ref
Console.WriteLine( x );
}
17
C# Classes
A C# class plays dual roles:
Program module: containing a list of (static)
method declarations and (static) data fields
Design for generating objects
• It is the model or pattern from which objects are created
• Supports two techniques which are essence of objectoriented programming
– “data encapsulation” (for abstraction)
– “inheritance” (for code reuse)

18
User-Defined Class
A user-defined class is also called a user-defined
type
class written by a programmer

A class encapsulates (wrap together) data and
methods:
• data members (member variables or instance variables)
• methods that manipulate data members

19
Objects
An object has:
state - descriptive characteristics
behaviors - what it can do (or be done to it)

For example, consider a coin in a computer game
The state of the coin is its current face (head or tail)
The behavior of the coin is that it can be flipped

Note the interactions between state and behaviors
the behavior of an object might change its state
the behavior of an object might depend on its state

20
Defining Classes
Use Project < Add Class to add a new class to your project

A class contains data declarations and method
declarations
class MyClass
public int x, y;
private char ch;

Data declarations

Method declarations
Member (data/method) Access Modifiers
public : member is accessible outside the class
private : member is accessible only inside the
class definition
21
Data Declarations
You can define two types of variables in a class but not in any
method (called class variables)
static class variables
nonstatic variables are called instance variables (fields)
because each instance (object) of the class has its own copy
class variables can be accessed in all methods of the class

Comparison: Local variables
• Variables declared within a method or within a block statement
• Variables declared as local variables can only be accessed in
the method or the block where they are declared

22
Method Declarations
A class can define many types of methods, e.g.,
Access methods : read or display data

Predicate methods : test the truth of conditions
Constructors
• initialize objects of the class
• they have the same name as the class
– There may be more than one constructor per class (overloaded
constructors)

• can take arguments
• they do not return any value
– it has no return type, not even void

23
Creating and Accessing Objects
We use the new operator to create an object
Random myRandom;
myRandom = new Random();

This calls the Random constructor, which is
a special method that sets up the object

Creating an object is called instantiation
An object is an instance of a particular class

To call a method on an object, we use the
variable (not the class), e.g.,
Random generator1 = new Random();
int num = generate1.Next();

24
The Dual Roles of C# Classes
Program modules:

• a list of (static) method declarations and (static) data
fields
• To make a method static, a programmer applies the
static modifier to the method definition
• The result of each invocation of a class method is
completely determined by the actual parameters (and
static fields of the class)
• To use a static method:
ClassName.MethodName(…);

Design for generating objects:
• Create an object
• Call methods of the object:
objectName.MethodName(…);

25
Creating and Accessing Objects
We use the new operator to create an object
Random myRandom;
myRandom = new Random();

This calls the Random constructor, which is
a special method that sets up the object

Creating an object is called instantiation
An object is an instance of a particular class

To call an (instance) method on an object, we
use the variable (not the class), e.g.,
Random generator1 = new Random();
int num = generate1.Next();

26
Method Declarations
Access methods : read or display data
Predicate methods : test the truth of conditions
Constructors
• initialize objects of the class
• they have the same name as the class

– There may be more than one constructor per class (overloaded constructors)
– Even if the constructor does not explicitly initialize a data member, all data
members are initialized
» primitive numeric types are set to 0
» boolean types are set to false
» reference (class as type) types are set to null
– If a class has no constructor, a default constructor is provided
» It has no code and takes no parameters

• they do not return any value
– it has no return type, not even void

27
Using Access Modifiers to Implement
Encapsulation: Methods
Public methods present to the class’s clients a view of
the services that the class provides
• public methods are also called service methods

A method created simply to assist service
methods is called a support or helper method
• since a support method is not intended to be called by a
client, it should not be declared with public accessibility

28
The Effects of Public and Private Accessibility
public

private

variables

violate
Encapsulation
Unless properties

enforce
encapsulation

methods

provide services
to clients

support other
methods in the
class

29
Class example
using System;
using System.Collections.Generic;
using System.Text;

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class MyClass
{
public int a,b;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int first, second;
Console.Write("Enter first value");
first = Int32.Parse(Console.ReadLine());
Console.Write("Enter first value");
second = Int32.Parse(Console.ReadLine());

public MyClass(int a,int b) {
this.a = a;
this.b = b;
}
public void print() {
Console.Write("The value is " + a + "
and " + b);
}
}
}

MyClass m = new MyClass(first, second);
m.print();
Console.ReadLine();
}}}
30

More Related Content

What's hot

A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
M Hussnain Ali
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 

What's hot (20)

C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
class and objects
class and objectsclass and objects
class and objects
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
Data types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in javaData types, Variables, Expressions & Arithmetic Operators in java
Data types, Variables, Expressions & Arithmetic Operators in java
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 

Viewers also liked (9)

Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
Lo2
Lo2Lo2
Lo2
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overriding
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Csc153 chapter 07
Csc153 chapter 07Csc153 chapter 07
Csc153 chapter 07
 
Object Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesObject Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference Types
 
Programming in c#
Programming in c#Programming in c#
Programming in c#
 
Slideshare.Com Powerpoint
Slideshare.Com PowerpointSlideshare.Com Powerpoint
Slideshare.Com Powerpoint
 

Similar to Visula C# Programming Lecture 6

Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
Palak Sanghani
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
sotlsoc
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
5. c sharp language overview part ii
5. c sharp language overview   part ii5. c sharp language overview   part ii
5. c sharp language overview part ii
Svetlin Nakov
 
C# Language Overview Part II
C# Language Overview Part IIC# Language Overview Part II
C# Language Overview Part II
Doncho Minkov
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 

Similar to Visula C# Programming Lecture 6 (20)

Lec4
Lec4Lec4
Lec4
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
C# overview part 2
C# overview part 2C# overview part 2
C# overview part 2
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
5. c sharp language overview part ii
5. c sharp language overview   part ii5. c sharp language overview   part ii
5. c sharp language overview part ii
 
Object and class
Object and classObject and class
Object and class
 
C# Language Overview Part II
C# Language Overview Part IIC# Language Overview Part II
C# Language Overview Part II
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on Python
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Chap08
Chap08Chap08
Chap08
 
Java class
Java classJava class
Java class
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Delegate
DelegateDelegate
Delegate
 

Recently uploaded

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 

Recently uploaded (20)

Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
Research Methods in Psychology | Cambridge AS Level | Cambridge Assessment In...
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 

Visula C# Programming Lecture 6

  • 2. Classes/Methods C# Framework Class Library (FCL) defines many classes, e.g., Console MessageBox Int32 Math The definition of a class includes both methods and data properties: methods, e.g., • Console.Write( ) • Console.WriteLine( ) • Int32.Parse( ) properties, e.g., • • • • Int32.MinValue Int32.MaxValue Math.PI Math.E 2
  • 3. Methods A method should provide a well-defined, easy-tounderstand functionality A method takes input (parameters), performs some actions, and (sometime) returns a value Example: invoking the WriteLine method of the Console class: Console.WriteLine ( "Whatever you are, be a good one.“ ); method class dot Information provided to the method (parameters) 3
  • 4. Example: Math Class Methods Method Abs( x ) Description absolute value of x Ceiling( x ) rounds x to the smallest integer not less than x Cos( x ) trigonometric cosine of x (x in radians) Exp( x ) exponential method ex Floor( x ) Log( x ) Max( x, y ) Min( x, y ) Pow( x, y ) Sin( x ) Sqrt( x ) Tan( x ) Example Abs( 23.7 ) is 23.7 Abs( 0 ) is 0 Abs( -23.7 ) is 23.7 Ceiling( 9.2 ) is 10.0 Ceiling( -9.8 ) is -9.0 Cos( 0.0 ) is 1.0 Exp( 1.0 ) is approximately 2.7182818284590451 Exp( 2.0 ) is approximately 7.3890560989306504 rounds x to the largest integer Floor( 9.2 ) is 9.0 not greater than x Floor( -9.8 ) is -10.0 natural logarithm of x (base e) Log( 2.7182818284590451 ) is approximately 1.0 Log( 7.3890560989306504 ) is approximately 2.0 larger value of x and y Max( 2.3, 12.7 ) is 12.7 (also has versions for float, Max( -2.3, -12.7 ) is -2.3 int and long values) smaller value of x and y Min( 2.3, 12.7 ) is 2.3 (also has versions for float, Min( -2.3, -12.7 ) is -12.7 int and long values) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 Pow( 9.0, .5 ) is 3.0 trigonometric sine of x Sin( 0.0 ) is 0.0 (x in radians) square root of x Sqrt( 900.0 ) is 30.0 Sqrt( 9.0 ) is 3.0 trigonometric tangent of x Tan( 0.0 ) is 0.0 (x in radians) Commonly used Math class methods. 4
  • 5. Methods Provide Abstraction and Reuse An abstraction hides (or ignores) the right details at the right time A method is abstract in that we don't really have to think about its internal details in order to use it e.g., we don't have to know how the WriteLine method works in order to invoke it Why abstraction? Divide and conquer Reuse Easier to understand 5
  • 6. Method Declaration: Header A method declaration begins with a method header class MyClass { … static int SquareSum( int num1, int num2 ) parameter list method name The parameter list specifies the type and name of each parameter return type The name of a parameter in the method properties declaration is called a formal argument 6
  • 7. Method Declaration: Body The method header is followed by the method body class MyClass { … static int SquareSum(int num1, int num2) { int sum = num1 + num2; return sum * sum; } … } 7
  • 8. The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type The return statement specifies the value that will be returned Its expression must conform to the return type 8
  • 9. Calling a Method Each time a method is called, the actual arguments in the invocation are copied into the formal arguments int num = SquareSum (2, 3); static int SquareSum (int num1, int num2) { int sum = num1 + num2; return sum * sum; } 9
  • 10. Class Methods (a.k.a. Static Methods) Previously we use class mainly to define related methods together: For example all math related methods are defined in the Math class The methods we have seen are defined as static (or class) methods To make a method static, a programmer applies the static modifier to the method definition The result of each invocation of a class (static) method is completely determined by the actual parameters 10
  • 11. Method Overloading The following lines use the WriteLine method for different data types: Console.WriteLine ("The total is:"); double total = 0; Console.WriteLine (total); Method overloading is the process of using the same method name for multiple methods Usually perform the same task on different data types Example: The WriteLine method is overloaded: WriteLine (String s) WriteLine (int i) WriteLine (double d) … 11
  • 12. Method Overloading: Signature The compiler must be able to determine which version of the method is being invoked This is by analyzing the parameters, which form the signature of a method The signature includes the number, type, and order of the parameters The return type of the method is not part of the signature 12
  • 13. Method Overloading Version 1 Version 2 double TryMe (int x) { return x + .375; } double TryMe (int x, double y) { return x*y; } Invocation result = TryMe (25, 4.32) 13
  • 14. Parameters: Modifying Formal Arguments You can use the formal arguments (parameters) as variables inside the method Question: If a formal argument is modified inside a method, will the actual argument be changed? static int Square ( int x ) { x = x * x; return x; } static void Main ( string[] args ) { int x = 8; int y = Square( x ); Console.WriteLine ( x ); } 14
  • 15. Parameter Passing If a modification on the formal argument has no effect on the actual argument, it is call by value If a modification on the formal argument can change the actual argument, it is call by reference 15
  • 16. Call-By-Value and Call-By-Reference in C# Depend on the type of the formal argument For the simple data types, it is call-by-value Change to call-by-reference The ref keyword and the out keyword change a parameter to call-by-reference • If a formal argument is modified in a method, the value is changed • The ref or out keyword is required in both method declaration and method call • ref requires that the parameter be initialized before enter a method while out requires that the parameter be set before return from a method 16
  • 17. Example: ref static void Foo( int p ) {++p;} static void Main ( string[] args ) { int x = 8; Foo( x ); // a copy of x is made Console.WriteLine( x ); } static void Foo( ref int p ) {++p;} static void Main ( string[] args ) { int x = 8; Foo( ref x ); // x is ref Console.WriteLine( x ); } 17
  • 18. C# Classes A C# class plays dual roles: Program module: containing a list of (static) method declarations and (static) data fields Design for generating objects • It is the model or pattern from which objects are created • Supports two techniques which are essence of objectoriented programming – “data encapsulation” (for abstraction) – “inheritance” (for code reuse) 18
  • 19. User-Defined Class A user-defined class is also called a user-defined type class written by a programmer A class encapsulates (wrap together) data and methods: • data members (member variables or instance variables) • methods that manipulate data members 19
  • 20. Objects An object has: state - descriptive characteristics behaviors - what it can do (or be done to it) For example, consider a coin in a computer game The state of the coin is its current face (head or tail) The behavior of the coin is that it can be flipped Note the interactions between state and behaviors the behavior of an object might change its state the behavior of an object might depend on its state 20
  • 21. Defining Classes Use Project < Add Class to add a new class to your project A class contains data declarations and method declarations class MyClass public int x, y; private char ch; Data declarations Method declarations Member (data/method) Access Modifiers public : member is accessible outside the class private : member is accessible only inside the class definition 21
  • 22. Data Declarations You can define two types of variables in a class but not in any method (called class variables) static class variables nonstatic variables are called instance variables (fields) because each instance (object) of the class has its own copy class variables can be accessed in all methods of the class Comparison: Local variables • Variables declared within a method or within a block statement • Variables declared as local variables can only be accessed in the method or the block where they are declared 22
  • 23. Method Declarations A class can define many types of methods, e.g., Access methods : read or display data Predicate methods : test the truth of conditions Constructors • initialize objects of the class • they have the same name as the class – There may be more than one constructor per class (overloaded constructors) • can take arguments • they do not return any value – it has no return type, not even void 23
  • 24. Creating and Accessing Objects We use the new operator to create an object Random myRandom; myRandom = new Random(); This calls the Random constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class To call a method on an object, we use the variable (not the class), e.g., Random generator1 = new Random(); int num = generate1.Next(); 24
  • 25. The Dual Roles of C# Classes Program modules: • a list of (static) method declarations and (static) data fields • To make a method static, a programmer applies the static modifier to the method definition • The result of each invocation of a class method is completely determined by the actual parameters (and static fields of the class) • To use a static method: ClassName.MethodName(…); Design for generating objects: • Create an object • Call methods of the object: objectName.MethodName(…); 25
  • 26. Creating and Accessing Objects We use the new operator to create an object Random myRandom; myRandom = new Random(); This calls the Random constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class To call an (instance) method on an object, we use the variable (not the class), e.g., Random generator1 = new Random(); int num = generate1.Next(); 26
  • 27. Method Declarations Access methods : read or display data Predicate methods : test the truth of conditions Constructors • initialize objects of the class • they have the same name as the class – There may be more than one constructor per class (overloaded constructors) – Even if the constructor does not explicitly initialize a data member, all data members are initialized » primitive numeric types are set to 0 » boolean types are set to false » reference (class as type) types are set to null – If a class has no constructor, a default constructor is provided » It has no code and takes no parameters • they do not return any value – it has no return type, not even void 27
  • 28. Using Access Modifiers to Implement Encapsulation: Methods Public methods present to the class’s clients a view of the services that the class provides • public methods are also called service methods A method created simply to assist service methods is called a support or helper method • since a support method is not intended to be called by a client, it should not be declared with public accessibility 28
  • 29. The Effects of Public and Private Accessibility public private variables violate Encapsulation Unless properties enforce encapsulation methods provide services to clients support other methods in the class 29
  • 30. Class example using System; using System.Collections.Generic; using System.Text; using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication3 { class MyClass { public int a,b; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { int first, second; Console.Write("Enter first value"); first = Int32.Parse(Console.ReadLine()); Console.Write("Enter first value"); second = Int32.Parse(Console.ReadLine()); public MyClass(int a,int b) { this.a = a; this.b = b; } public void print() { Console.Write("The value is " + a + " and " + b); } } } MyClass m = new MyClass(first, second); m.print(); Console.ReadLine(); }}} 30