Professional Documents
Culture Documents
Methods: Main Function To Run
Methods: Main Function To Run
Methods
Overview
A method is code, often referred as function in other programming
languages. Every program must have a Main() function to run.
- Reusable code.
- Easy to test.
- Modifications to a method do not affect the calling program.
- One method can accept many different inputs.
Declaring a Method
To use a method, you need to declare (i.e. create a function)
the method and then call (i.e. use) it.
Named Arguments
When inputting arguments into a method, order of input matters,
to overcome this, it can be specified which arguments the value
goes to:
Passing Arguments
There are three ways to pass arguments to a method when the
method is called: By value, by reference, and as output.
By value:
static void Main(string[] args)
{int a = 3; Sqr(a); Console.WriteLine(a);}
static void Sqr(int x)
{x = x*x;}
The output of this code will still be 3, since Sqr() did not do
anything with a, first of all because it doesn’t return a value,
and also, because to assign a value to a we would write:
a = Sqr(a)
By reference: keyword: ref
static void Main(string[] args)
{int a = 3; Sqr(ref a); Console.WriteLine(a);}
static void Sqr(ref int x)
{x = x*x;}
The output of this code will be 9, because when we use the Sqr()
method, we refer the output value to a, and hence it
automatically assigns it to it.
Overloading
Method overloading is when multiple methods have same name, but
different parameters.
This is one example of it. The method Print() would only accept
integer values, if only the first method would be declared. But
with help of second method, now Print() accepts doubles as well.
Recursion
Recursion is when a method is being called inside itself. It is
a useful tool that can for example calculate factorials.