Till now, we were writing our codes in the Main method. In this chapter, you will learn to create your own methods.
Imagine, you are making a game. And you need to display the score frequently. One solution is to write the whole code to display the score, again and again, whenever wanted. But there is another and better solution using functions (or methods). Define that whole code in a method (or function) and call it whenever you want. Simple!
A method is nothing but a group of codes written together and given a name. And these can be called anytime in the Main method without typing the whole code.
Writing methods saves us from writing the same code snippet again and again and also make our code a lot more readable and neat. We have already use predefined methods like WriteLine, ReadLine, Sin, etc. Let's learn to create our own methods.
Declaration of Methods
return_type MethodName ( parameters ) ;
As an example, suppose we have to calculate the average of 2 numbers, num1 and num2. The numbers are of type integer and average is of type double. Then we will pass the numbers to a method that will return (gives us back) the average value of those numbers. We will declare that method as follows:
double Average(int num1,int num2 );
Here, the method named Average is taking num1 and num2 of integer type as input and then returning the average value of type double after calculating it.
Defining Method
The syntax for defining a method is
return_type MethodName ( parameters )
{
//code
}
Let's see the average function that we defined above.
float Average(int num1, int num2)
{
double avg; /* declaring local variable */
avg = (num1 + num2)/2.0;
return avg; /* returning the average value */
}
Variables declared inside a method are called local variables. A local variable can only be used in the method in which it is declared. It has no use outside the method. For example, in our case, avg is a local variable and is invalid outside the method.
Therefore, we wrote
int along with num1 and num2.
return avg; → This means that this method will give us or return us the variable avg (or value of the variable avg) which is of type double. You will understand this more clearly from examples.
Calling Method
To use a method, we need to call it. Once we call a method, it performs its operations (executes statements inside it).
To call a method, we need to specify the method name along with pass the argument required by the method.
MethodName ( arguments ) ;
So we will call our average function as shown below:
Average(num1, num2);
Now, let's combine all to take out the average of 2 numbers using a method.
using System; class Test { static double Average(int num1, int num2) { double avg; avg = (num1+num2)/2.0; return avg; } static void Main(string[] args) { int a, b; double c; Console.WriteLine("Enter first number"); a = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter second number"); b = Convert.ToInt32(Console.ReadLine()); c = Average(a, b); //calling the Average method and storing its value in c Console.WriteLine($"Average is {c}"); } }
static double Average(int num1, int num2) → You will learn about static in later chapters. For now, just ignore it. Our method named Average will give us back (return) a double and will take two integers - num1 and num2 as input. num1 and num2 are the parameters of the method.
Inside this method, it is calculating average of num1 and num2 and storing it in a variable avg -
avg = (num1+num2)/2.0;.
After this, it is returning this value -
return avg; because we have stated that our method will return a double during the time of declaration.
return keyword is used to make a method return something. The execution of a method stops as soon as after returning anything from it.
Now, we need to use this method. We will call this method and pass two integers to it. The values passed to a method are called arguments.
By writing
c = Average(a, b), we are calling the method Average method with 2 arguments (a and b). Now, Average is called and it calculated and returned the average value of num1 and num2.
We have passed
Average(a, b) and the method is taking
Average(num1, num2). Inside the method, num1 will have a value of the variable a and num2 will have the value of the variable b. Actually, we are not even passing the real variables but only their values.
As the method is returning a double, and here it is 4.5, so, this expression (
c = Average(a, b)) will be equivalent to
c = 4.5, since 4.5 is returned by the function and its value gets stored in a variable c.
It is not necessary for a method to return data. A method can not return anything from it and in that case, its return type would be
void. Let's look at the following example:
using System; class Test { static void Display(int n) { Console.WriteLine(n); } static void Main(string[] args) { Display(5); } }
void means that the method will not return anything.
It is also possible to define a method without any arguments. Let's see its example.
using System; class Test { static void Display() { Console.WriteLine("Function with no argument"); } static void Main(string[] args) { Display(); } }
As we saw, there is no argument given to the method Display.
Calling a Method Inside Another
Yes, we can call a method inside another method. We have already done this. We were calling our methods inside the Main method. Now, look at an example in which there are two user-defined methods. And we will call one inside another.
using System; class Test { static bool Div2(int a) { if(a%2 == 0) return true; return false; } static void Div6(int b) { if(Div2(b) && b%3==0) Console.WriteLine("Yes, the number is divisible by 6."); else Console.WriteLine("No, the number is not divisible by 6."); } static void Main(string[] args) { Div6(12); Div6(25); } }
A number is divisible by 6 if it is divisible by both 2 and 3. We have a function Div2 which return
true if the given number is divisible by 2. Another function that we have defined is Div6 which calls Div2 inside itself.
if(Div2(b)==1 && b%3 == 0) → In our case, b and thus a are 12 in the first case and 25 is the next case. So, if Div2 returns
true, the number is divisible by 2. And if
b%3==0 is true, b is divisible by 3 also. So if the number is divisible by both 2 and 3, then it is divisible by 6 also.
Let's take one more example of a method calling a different method.
using System; class Test { static void Display1() { Console.WriteLine("Display1"); } static void Display2() { Display1(); Console.WriteLine("Display2"); } static void Main(string[] args) { Display2(); } }
Inside the Display2 method, we have called Display1 method. Inside the Main method, the first statement is
Display2();. So, the codes of Display2 method will be executed first. Inside Display2 method, the first statement is
Display1();. So, the codes of Display1 method got executed and then the rest of the statements of Display2 method got executed.
Recursion
We have called a method into a different one. Recursion is the calling of a method within the same method.
Let's consider an example in which we have to calculate the factorial of a number.
The factorial of a number n is the product of all the natural numbers till n. For example, the factorial of 5 is 1*2*3*4*5 = 120, the factorial of 2 is 1*2 = 2. The factorial of both 0 and 1 is 1.
using System; class Test { static int Factorial(int a) { if(a==0 || a==1) return 1; else return a*Factorial(a-1); } static void Main(string[] args) { int n; Console.WriteLine("Enter a number"); n = Convert.ToInt32(Console.ReadLine()); int fact = Factorial(n); Console.WriteLine($"Factorial of {n} is {fact}"); } }
Since we passed n to the function Factorial, therefore the value of a in that method is of the value of n. If the value of the integer a is 0 or 1,
return 1; will return 1. Otherwise if the integer a is greater than 1, then
a*Factorial(a-1) multiplies a with the factorial of 'a-1'.
For example, if the number is 4, then
a*Factorial(a-1) implies
4*Factorial(3). So by writing
a*Factorial(a-1), we are again calling the method Factorial inside itself but this time the argument is a-1 i.e.
Factorial(a-1).
So if we give 0 to the method Factorial, it will return us 1.
If we give 1, it will again return 1.
Now, give 2.
This time the statement in the body of 'else' will be executed and it has to return
a*Factorial(a-1) i.e.
2*Factorial(1). So, it will again call Factorial (as
Factorial(1)) which is 1. Finally, it will return 2*1 i.e. 2.
Now, try this with 3. This time, it will return
3*Factorial(2). Again it will call
Factorial(2) which will return
2*Factorial(1). So the expression will be
return 3*2*Factorial(1) which is
3*2*1 ( since
Factorial(1) will return 1 ).
For 4, the expression will be
4*Factorial(3).
Calling
Factorial(3) will return
4*3*Factorial(2) (since
Factorial(3) will return
3*factorial(2) ).
Again calling
Factorial(2) will return
4*3*2*Factorial(1).
Thus, at last,
4*3*2*1 or 24 will be returned.
Hopefully, you have understood this. Most of the programmers find this difficult in their beginning days. So, congrats!
C# Call By Reference
As stated earlier, when we pass a variable to a method, its value is passed (or one can say a copy of it) and not the original variable. It means that if we make any change to the variable, it won't be reflected back. This is pass by value i.e., we are just passing the values of variables and not the original variables. Let's look at an example trying to change the value of a variable inside a method.
using System; class Test { static void Change(int a) { a = 5; Console.WriteLine(a); } static void Main(string[] args) { int n = 10; Change(n); Console.WriteLine(n); } }
As you can see that the value of the variable was changed inside the method but the change is not reflecting outside the method.
If we ever need to change the value of a variable inside a method which we want to reflect outside also, we pass the reference of variables called pass by reference.
By reference, we mean the reference to the memory location of a variable. So, we will basically pass a reference to the memory location where the variable is stored. Thus, any change made to it will also reflect in the real variable. It is like passing the real variable to methods (and not their copies).
C# ref Parameter
We use
ref keyword to pass the argument as reference-type. Let's look at an example.
using System; class Test { static void Change(ref int a) { a = 5; Console.WriteLine(a); } static void Main(string[] args) { int n = 10; Change(ref n); Console.WriteLine(n); } }
You can see that this time the change in the variable is also reflecting outside the method.
C# out Parameter
out keyword is also used for pass by reference. It is also like
ref keyword and the value change inside the method will be reflected outside but the difference is that we can pass a variable without even assigning any value to it using the
out keyword i.e., without even initializing a variable.
Let's look at an example.
using System; class Test { static void Change(out int x, out int y) { x = 5; y = 5; Console.WriteLine(x); Console.WriteLine(y); } static void Main(string[] args) { int a = 10; int b; Change(out a, out b); } }
You can see that we passed the variable b without even assigning any value to it.
In case of any doubt, you can ask your questions on our Discussion Forum.