You are on page 1of 38

Core C# Programming

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();

• These calls aren’t allowed.


// MyMethodNoReturnedData() does not return any information.
myNumber = MyMethodNoReturnedData();
Methods - Parameters
• Methods can also accept information through
parameters
• Parameters are declared in a similar way to variables.
• By convention, parameter names always begin with a
lowercase letter in any language.
Methods – Parameters
private int AddNumbers(int number1, int number2)
{
return number1 + number2;
}
Methods - Parameters
• When calling a method, you specify any required
parameters in parentheses
• If no parameters are required use an empty set of
parentheses
Method Overloading
• C# supports method overloading
• Method overloading allows you to create more than one
method with the same name but with a different set of
parameters.
• When you call the method, the CLR automatically
chooses the correct version by examining the parameters
you supply.
Method Overloading
• This technique allows you to collect different versions of several
methods together.
• For example, rather than creating these three methods
• GetAllProductsPrice()
• GetProductPriceInCategory()
• GetActiveProductsPrice()
• You could create three versions of the GetProductsPrice()
method.
Method Overloading
• Each of these methods would have the same name but a
different signature
• The three GetProductPrice() methods will be as
follows:
• GetProductPrice()
• GetProductPrice(int ID)
• GetProductPrice(string name)
Method Overloading
• You cannot overload a method with versions that have
the same signature
• When you call an overloaded method, the version that
matches the parameter list you supply is used.
• If no version matches, an error occurs.
Optional and Named Parameters
• In addition to method overloading, C# support
optional parameters
• The objective of optional parameters is the same as
method overloading – flexibility
• An optional parameter is any parameter that has a
default value.
Optional and Named Parameters
• If a method has normal parameters and optional
parameters, the optional parameters must be placed at
the end of the parameter list.
• Example,
string GetUserName(int ID, bool shortForm = false)
Optional and Named Parameters
• Here, the shortForm parameter is optional,
• This gives you two ways to call the GetUserName()
method
• name = GetUserName(401, true);
• name = GetUserName(401);
Optional and Named Parameters
• There are situation where there are multiple optional
parameters for a method
• The easiest option is to pick out the parameters you want
to set by name.
• This feature is called named parameters, and to use it you
simply add the parameter name followed by a colon (:),
followed by the value
Optional and Named Parameters
• For example,
decimal GetSalesTotalForRegion(int regionID,
decimal minSale = 0, decimal maxSale = 100,
bool includeTax = false)
• One possible way to call this method would be
total = GetSalesTotalForRegion(523, maxSale: 5000);
Understanding C# Arrays
• An array is a set of
• Data items accessed using a numerical index
• Contiguous data points of the same type
• Declaring, filling, and accessing an array with C# is
quite straightforward.
• The lower bound of an array always begins at 0
Understanding C# Arrays
• If you declare an array, but do not explicitly fill each
index, each item will be set to the default value of the
data type
• You can fill the items of an array using C# array
initialization syntax.
• In such cases you don’t need to specify the size of the
array explicitly as it can be inferred from the elements
Implicitly Typed Local Arrays
• Recall that the var keyword allows you to define a
variable, whose underlying type is determined by the
compiler.
• The var keyword can be used to define implicitly typed
local arrays.
• You can allocate a new array variable without specifying
the type contained within the array itself
Implicitly Typed Local Arrays
• The items in the array’s initialization list must be of the
same underlying type
• An implicitly typed local array does not default to
System.Object
• Thus, the following generates a compile-time error
var d = new[] { 1, "one", 2, "two", false };
The System.Array Base Class
• Every array you create gathers much of its functionality
from the System.Array class.
• Using these common members, you are able to operate
on an array using a consistent object model.
• The next table gives a list of some of the more
interesting members
Selected Members of System.Array
Member Meaning
Clear() This static method sets a range of elements in the array to empty values (0 for
numbers, null for object references, false for booleans).
CopyTo() This method is used to copy elements from the source array into the destination
array.
Length This property returns the number of items within the array.
Rank This property returns the number of dimensions of the current array
Reverse() This static method reverses the contents of a one-dimensional array.
Sort() This static method sorts a one-dimensional array of intrinsic types. If the elements
in the array implement the IComparer interface, you can also sort your custom
types
The enum Type
• An enum is a custom data type of name/value pairs
• When building a system, it is often convenient to
create a set of symbolic names that map to known
numerical values.
• C# supports the notion of custom enumerations for
this very reason.
The enum Type - Example
enum EmpType
{
Manager, // = 0
Grunt, // = 1
Contractor, // = 2
VicePresident // = 3
}
The enum Type
• The EmpType enumeration defines four named
constants, corresponding to discrete numerical values
• By default, the first element is set to the value zero (0),
followed by an n + 1 progression.
• You are free to change the initial value as you see fit
• Enumerations do not necessarily need to follow a
sequential ordering
enum Example –Begin with 102.
enum EmpType
{
Manager = 102,
Grunt, // = 103
Contractor, // = 104
VicePresident // = 105
}
enum Example – Non sequential
enum EmpType
{
Manager = 10,
Grunt, // = 1
Contractor, // = 100
VicePresident // = 9
}
Declaring enum Variables
• Once you have established the range and storage type of
your enumeration, you can use it in place of so called
“magic numbers.”
• Because enumerations are nothing more than a user-
defined data type, you are able to use them as function
return values, method parameters, local variables, and so
forth.
The System.Enum Type
• Enums in .NET gain functionality from the
System.Enum class type.
• This class defines a number of methods that allow you
to interrogate and transform a given enumeration.
• One helpful method is the static
Enum.GetUnderlyingType()

You might also like