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