Methods in C#

 

Description – In this article, we will learn about the Methods in Csharp and also the Different types of methods that are available in Csharp and also their implementation with the examples.

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 below diagram which shows the overview of the below discussion..

2016-01-10_12-34-13

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:

access_specifier return_type method_name (data_type parameter_name)

{

method_body;

}

public void Calculation()
    {
        Console.WriteLine("Simple Method.");
    }

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 that 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 paratheses 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#.

2016-01-10_12-38-19

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:-

using System;
 
class Program
{
    public static void Main(string[] args)
    {
        var p = new Program();
        p.Calculation(); //We call the Instance method calculation using 'p' which is the instance of Program Class
    }
    
    //Calculation method is an instance method
    public void Calculation()
    {
        Console.WriteLine("Simple Method.");
    }
 
}

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 shown in the below sample program. If you try to access the static method using an instance, it gives a compilation error.

using System;
class Program
{
    public static void Main(string[] args)
    {
        Program.Calculation(); //Static Method calculation is called using the class name directly as it cannot to be instanciated.
    }
    
    //Calculation method is a static method
    public static void Calculation()
    {
        Console.WriteLine("Simple Method.");
    }
}

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. Lets understand this with the help of the below mentioned code snippet.

using System;
class Program
{
    public static void Main(string[] args)
    {
        var result = Calculation(20, 50);
        Console.WriteLine(result);
    }
    public static int Calculation(int x, int y)
    {
        return x + y;
    }
}

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 shown in the below example snippet.

using System;
class Program
{
    public static void Main(string[] args)
    {
        var a = 20;
        var b = 50;
        Calculation(ref a, ref b);
        Console.WriteLine(a + b);
    }
    public static void Calculation(ref int x, ref int y)
    {
        x = 80;
        y = 20;
    }
}

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 the 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. Lets understand this with the below code snippet.

using System;
class Program
{
    public static void Main(string[] args)
    {
        var a = new int[4];
        a[0] = 10;
        a[1] = 20;
        a[2] = 30;
        a[3] = 40;
        ArrayMethod(a);
    }
    public static void ArrayMethod(int[] arr)
    {
        Console.WriteLine($"The numbers of elements in the array are {arr.Length}");
        foreach (var i in arr)
        {
            Console.WriteLine(i);
        }
    }
}

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 more 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.

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

Earlier we use 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 then 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 paramters to achieve our goal. Lets understand this with the example below.

using System;
class Program
{
    public static void Main(string[] args)
    {
        int a, b, c, d;
        Calculator(80, 40, out a, out b, out c, out d);
        Console.WriteLine($"The Sum is : {a}");
        Console.WriteLine($"The Product is : {b}");
        Console.WriteLine($"The Division is : {c}");
        Console.WriteLine($"The Subtract is : {d}");
    }
    public static void Calculator(int x, int y, out int sum, out int product, out int division, out int subtract)
    {
        sum = x + y;
        product = x * y;
        division = x / y;
        subtract = x - y;
    }
}

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 us 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.

using System;
class Program
{
    public static void Main(string[] args)
    {
        var a = new int[4];
        a[0] = 10;
        a[1] = 20;
        a[2] = 30;
        a[3] = 40;
        ArrayMethod();
    }
    public static void ArrayMethod(params int[] arr)
    {
        Console.WriteLine($"The numbers of elements in the array are {arr.Length}");
        foreach (var i in arr)
        {
            Console.WriteLine(i);
        }
    }
}

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 is 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.

 

Advertisements