Methods In C#

Agenda

  • What are methods in C#?
  • Different types of Methods in C#
  • Method Parameters in C#
  • Types of Method Parameters in C#
  • Params keyword in C#
  • Parameters and Arguments

Please have a look at the following diagram which shows the overview of the below discussion.

 
Methods
 
These are the user defined / pre-defined code blocks which contains a list of statements to be executed whenever they are called / executed. These are very useful if a same logic is to be implemented many times within a same program or in other programs. It helps to reduce the code redundancy. It helps a programmer to follow the very famous software development approach, i.e. DRY (Don't Repeat Yourself). They are also referred to as functions.

Syntax to declare a method:

  1. access_specifier return_type method_name (data_type parameter_name)    
  2. {  
  3.    method_body;    
  4. }  
  1. public void Calculation()  
  2. {  
  3.     Console.WriteLine("Simple Method.");  
  4. }  

Access Specifiers

We will not go into details of these but for this session, please remember that they are of 5 types:

  • public,
  • private,
  • protected,
  • internal,
  • internal protected.

We will go into their details in a later tutorial.

Return Type
 
It tells your method what type of value it has to return to the calling program. It can be any data type if your method is returning a value and its value will be 'void' if your method is not returning anything to the calling program.

Method Name
 
It can be anything as per your choice except the reserved keywords of C# language.

Parameters
 
They are the special values that a user has to supply at the time of calling the function in the program, if parameters are defined for that function as they are optional. The parameters are always defined in the parenthesis following the function name. It needs a data type for the value that the user will supply and the name of parameters can be anything except the reserved keywords of C#.

 

Method Body
 
It is the main body of a function where the main logic is defined.

Different Types of Methods in C#

  • Instance Methods
  • Static Methods

Instance Methods
 
These methods are the methods which needs to be called with the help of the instance of the class in which they are being called.

Sample program:

  1. using System;  
  2.    
  3. class Program  
  4. {  
  5.     public static void Main(string[] args)  
  6.     {  
  7.         var p = new Program();  
  8.         p.Calculation(); //We call the Instance method calculation using 'p' which is the instance of Program Class  
  9.     }  
  10.       
  11.     //Calculation method is an instance method  
  12.     public void Calculation()  
  13.     {  
  14.         Console.WriteLine("Simple Method.");  
  15.     }  
  16.    
  17. }  
Static Methods

These methods are the methods which can be called simply without the instance of the class in which they are being called. They are declared with a 'static' keyword as in the following sample program. If you try to access the static method using an instance, it gives a compilation error.
  1. using System;  
  2. class Program  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         Program.Calculation(); //Static Method calculation is called using the class name directly as it cannot to be instanciated.  
  7.     }  
  8.       
  9.     //Calculation method is a static method  
  10.     public static void Calculation()  
  11.     {  
  12.         Console.WriteLine("Simple Method.");  
  13.     }  
  14. }  

Method Parameters

These are the values that needs to be supplied along with method at the time of its execution. They are really helpful in case we need to use the same method for different calculations. Their declaration is already mentioned at the starting of this article.

Types of Method parameters

They are of 4 types:
  • Value type parameters
  • Reference type parameters
  • Array Parameters
  • Output parameters

Value type parameters
 
These are the parameters whose actual value is supplied to the method at the time of its execution. Let us understand this with the help of the following code snippet.

  1. using System;  
  2. class Program  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         var result = Calculation(20, 50);  
  7.         Console.WriteLine(result);  
  8.     }  
  9.     public static int Calculation(int x, int y)  
  10.     {  
  11.         return x + y;  
  12.     }  
  13. }  

So, in the above snippet, Calculation method is expecting two parameters x,y of type integer. And also notice that the return type of this method is now 'int'. So, this method should return integer value, so the return statement is used in the body of this method.

Now, the value 20 and 50 are passed for x and y variables, and its value that is returned by the method is stored in a variable named result and then printed on the console. So, this is called as Value type parameters where the actual values are passed for the parameters like 20 and 50 here.

Reference type parameters
 
These are the parameters which points to the address location of the variables rather than their actual values. They are declared using the 'ref' keyword. It is to be noted that ref keyword must be supplied at the time of function declaration and its implementation both as in the following code snippet.

  1. using System;  
  2. class Program  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         var a = 20;  
  7.         var b = 50;  
  8.         Calculation(ref a, ref b);  
  9.         Console.WriteLine(a + b);  
  10.     }  
  11.     public static void Calculation(ref int x, ref int y)  
  12.     {  
  13.         x = 80;  
  14.         y = 20;  
  15.     }  
  16. }  

In the above snippet, the values of a and b in the main method are 20 and 50, after that we call the calculation method and passing parameter values as the reference type. These values will go to the Calculation method along with reference parameters and the values are changed to 80 and 20 respectively. Here, the a and b & x and y variables points to the same address locations. So, the values are altered and the result will be 100 as now the values of a and b are changed to 80 and 20.

Array parameters

These are the parameters that takes a complete array as an argument. Let us understand this with the following code snippet.

  1. using System;  
  2. class Program  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         var a = new int[4];  
  7.         a[0] = 10;  
  8.         a[1] = 20;  
  9.         a[2] = 30;  
  10.         a[3] = 40;  
  11.         ArrayMethod(a);  
  12.     }  
  13.     public static void ArrayMethod(int[] arr)  
  14.     {  
  15.         Console.WriteLine($"The numbers of elements in the array are {arr.Length}");  
  16.         foreach (var i in arr)  
  17.         {  
  18.             Console.WriteLine(i);  
  19.         }  
  20.     }  
  21. }  

In the above code, a is an array of length 4. We pass this array as an argument to the method ArrayMethod which expects an array as a parameter.

Also, I want to introduce you with a new feature of C# 6.0 which is string interpolation. This feature helps you to manage the code easily. Have you noticed that I have used a $ sign in the Console.WriteLine method, this $ sign is a string interpolator which allow us to put the direct variable name in the placeholders instead of 0,1,2.. and so on.

  1. Console.WriteLine("The number of elements in the array are {0}",arr.Length);  
  2. Console.WriteLine($"The numbers of elements in the array are {arr.Length}");  

Earlier we used the placeholder having the index values and then pass the variable values using a comma, but C# 6.0 allows us to use direct variable names as shown above.

Sounds good! Don't worry, I will be soon writing an article sharing all the cool features of C# 6.0 that helps you to increase your productivity.

Output Parameters
 
Suppose, you want a method to return you more than one value, a method can return a single value at the same time. They are declared using the 'out' keyword. So, in this type of case we make the return type of the method as void and use the output parameters to achieve our goal. Let us understand this with the example below.

  1. using System;  
  2. class Program  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         int a, b, c, d;  
  7.         Calculator(80, 40, out a, out b, out c, out d);  
  8.         Console.WriteLine($"The Sum is : {a}");  
  9.         Console.WriteLine($"The Product is : {b}");  
  10.         Console.WriteLine($"The Division is : {c}");  
  11.         Console.WriteLine($"The Subtract is : {d}");  
  12.     }  
  13.     public static void Calculator(int x, int y, out int sum, out int product, out int division, out int subtract)  
  14.     {  
  15.         sum = x + y;  
  16.         product = x * y;  
  17.         division = x / y;  
  18.         subtract = x - y;  
  19.     }  
  20. }  

In the above example, we use 4 output parameters and define their working in the method calculator's body. Then we access this method in the Main method, and get the calculated values in variables a, b, c, d. So, our method now returns with 4 values at the same time.

Params keyword

This is a keyword which you can use with a parameter of a function to make it optional. It makes sure that if the value of the parameter is not supplied, then the function will not give any error/issue. But it can be only one in the function and it should be the last parameter of that function. Also, it should be a single dimensional array. It means that it will work only with an array parameter.

  1. using System;  
  2. class Program  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         var a = new int[4];  
  7.         a[0] = 10;  
  8.         a[1] = 20;  
  9.         a[2] = 30;  
  10.         a[3] = 40;  
  11.         ArrayMethod();  
  12.     }  
  13.     public static void ArrayMethod(params int[] arr)  
  14.     {  
  15.         Console.WriteLine($"The numbers of elements in the array are {arr.Length}");  
  16.         foreach (var i in arr)  
  17.         {  
  18.             Console.WriteLine(i);  
  19.         }  
  20.     }  
  21. }  

Note that in the above example, the function ArrayMethod is not supplied with an argument but still this program works as params keyword made it optional.

Note: Parameters are the declarations and the values that will be passed to that parameter called an argument. So, in short, an Argument is the actual value of a Parameter.

If you like this article and think that it is helpful, then please share it so that it can help others also. 

Up Next
    Ebook Download
    View all
    Learn
    View all