Professional Documents
Culture Documents
Constructs
PART 2
Methods
• Methods are the most basic building block you can
use to organize your code.
• A method is a named grouping of one or more lines
of code.
• Ideally, each method will perform a distinct, logical
task.
Methods
• By breaking down your code into methods make it
easier to organize your code into classes and step into
the world of object-oriented programming.
• The first decision you need to make when declaring
a method is whether you want to return any
information.
Methods
• When you declare a method in C#
• The first part of the declaration specifies the data type of
the return value
• The Second part indicates the method name
• The method name is followed by parentheses
• If your method doesn’t return any information, you
should use the void keyword
Methods
// This method doesn’t return any information.
void MyMethodNoReturnedData()
{
// Code goes here.
}
Methods
// This method returns an integer.
int MyMethodReturnsData()
{
// As an example, return the number 10.
return 10;
}
Methods
• In the method definition we can specify a number of
modifiers
• These include accessibility modifiers such as public
and private
• Note that if you don’t specify accessibility, the
method is always private
Methods – with Accessibility keyword
private void MyMethodNoReturnedData()
{
// Code goes here.
}
Methods - parameter modifiers
• Modifiers can also be applied to parameters
• These modifiers are optional
• The list of C# parameter modifiers is presented in the
next table
Method parameter modifiers
Parameter Meaning
Modifier
(None) If a parameter is not marked with a parameter modifier, it is assumed to
be passed by value, meaning the called method receives a copy of the
original data.
out Output parameters must be assigned by the method being called, and
therefore, are passed by reference. If the called method fails to assign
output parameters, you are issued a compiler error.
ref The value is initially assigned by the caller and may be optionally
reassigned by the called method (as the data is also passed by reference).
No compiler error is generated if the called method fails to assign a ref
parameter.
Method parameter modifiers
Parameter Meaning
Modifier
params This parameter modifier allows you to send in a variable number of
arguments as a single logical parameter. A method can have only a single
params modifier, and it must be the final parameter of the method. In
reality, you might not need to use the params modifier all too often;
however, be aware that numerous methods within the base class libraries
do make use of this C# language feature.
Methods – invoking
• To invoke a method simply type the name of the method,
followed by parentheses
• If the method returns data, you have the option of using
the data it returns or just ignoring it
Methods – Invoking a method
• These calls are allowed.
MyMethodNoReturnedData();
MyMethodReturnsData();
int myNumber;
myNumber = MyMethodReturnsData();