Tuesday, May 19, 2020

C# Tutorial: 08 - Methods in C#

Tutorial: 08 - Methods in C#

Method is a block of code which have set of statements which performs some task(s). A method is executed with it is called by using its name and providing any required information by using parameters. Methods provides re-usability to code as you can call a method again and again as per your requirements.

Defining a Method
Here is a general syntax of a method in C#.
<Access Specifier> <Return Type> <Method Name>(Parameters) 
{
Statement(s)
}

Access Specifier are used to control access level or visibility of methods.
Return Type specifies what type of value will be returned by the method.
Method Name is an identifier which is used for identifying the method uniquely.
Parameters are used to provide additional data required by method while its execution.
Statement part contains actual task which will be performed by the method.
Lets see an example of a method which will take a number a parameter and will check whether
a number is even or odd.


Passing Parameters
You can pass additional information to a method by using parameters. You can pass as many
as required parameters to a method. Parameters can be of different data types or they can be of
same data type. See following example for Parameter Passing in which we are passing 3 different
parameters to a method named PrintNumbers.

Return Values
A method can return value after executing its statements. Return keyword is used in order to
return value from method. If you want nothing to be return, use void. Example for return values
are given below:


We will discuss about Access Specifiers with classes then we will also explore various examples
for controlling visibility of methods.

No comments:

Post a Comment