Topic : Passing Arguments to Methods: Call by Value | Call by Pointer | Call by Reference:

Passing Arguments To Function:

The Main objective of passing Argument to Methods is Message passing. The message passing is also known as communication between two Methods, that is between caller and called Methods. There are three Types by which we can pass values to the Methods. These Types are as follows:




The argument used to send values to Methods are known as input arguments. The arguments used to return result are from Methods, known as output Arguments. the Arguments used to send as well as return results are know as input-output arguments. While passing values to the Methods, the following conditions should be fulfilled.

  • The data type and a number of actual and formal arguments should be same both in the caller and called Methods. Extra arguments are discarded if they are declared. if the formal arguments are more than the actual arguments, then the extra arguments appear as garbage. Any mismatch in the data type will produce the unexpected result.



Passing argument to Methods

Here we take an example, this example will get two numbers from the user and swap these numbers. we will try to solve this example with all three Methods. (by value, by pointer, by reference).


Call by Value:

The default parameter passing Mechanism in C# is classified as Pass by Value also known as Call by Value This Means the value of the actual parameter is copied to the formal parameter for the purpose of executing the Method's code. Since it is working on a copy of the actual parameter, the Method's execution cannot affect the value of the actual parameter owned by the caller.

Let's have an simple example to clear that how Arguments Pass by Value to methods. in this example, we have an Method which required two number from user. when user will enter numbers, this Method will try to swap the numbers, and return it. have a deep look in this example:


/*Example: Arguments passing to methods by value:
 InfoBrother:*/

using System;

namespace passingArguments
{
    class ByValue
    {
        //swapping Method:
        public void swap(int x, int y)
        {
            int temp = x;  //put value of x into temp:
            x = y;        //put value of y into x;
            y = temp;     //put value of temp into y:
        }

        //main method:
        static void Main(string[] args)
        {
            ByValue obj = new ByValue();  

            int a = 10;
            int b = 20;
            Console.WriteLine("Before swapping: a = {0}, b = {1}", a, b);

            obj.swap(a, b);  //Method call to swap the values:
            Console.WriteLine("After swapping: a = {0}, b = {1}", a, b);

            Console.ReadKey();
        }
    }
}


In the Above example, did you Notice that the value of A and B is same after and before swapping. Because the value of the actual parameter is copied to the formal parameter for the purpose of executing the Method's code. Since it is working on a copy of the actual parameter, the Method's execution cannot affect the value of the actual parameter owned by the caller.



Call by Pointer ( * ):

Passing by Pointer also known as call by Pointer Method of passing arguments to a Method copies the address of an argument into the formal parameter. Inside the method, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by pointer, argument pointers are passed to the method just like any other value. so we Need to declare the method parameters as pointer types, which exchanges the values of the two integer variable pointed to by its arguments.
Let's have the same example that we used for "passing by value", but here we will pass the argument by Pointer. let's have a deep look in this example:



Now we are about to use Pointer in our program. Remember, whenever we will use pointer in our program, the code will be unsafe. so before getting start with this example, read about the unsafe code and pointer in our previous tutorial Pointers.



/*Example: Arguments passing to methods by Pointer:
 InfoBrother:*/

using System;

namespace passingArguments
{
    class ByPointer
    {
        //swapping Method:
        public unsafe void swap(int* x, int* y)
        {
            int temp = *x;  //put value of x into temp:
            *x = *y;        //put value of y into x;
            *y = temp;     //put value of temp into y:
        }

        //main method:
        static unsafe void Main(string[] args)
        {
            ByPointer obj = new ByPointer();  

            int a = 10;  //variable declaration:
            int b = 20;
            int* var1 = &a;  //pointer point to the address
            int* var2 = &b;  //of variables.
            
            Console.WriteLine("Before swapping: a = {0}, b = {1}", a, b);

            obj.swap(var1, var2);  //Method call to swap the values:
            Console.WriteLine("After swapping: a = {0}, b = {1}", a, b);

            Console.ReadKey();
        }
    }
}


In The above example, the value of A and B change indirectly after swapping. because at this time we didn't pass only value to method, but we pass the address of variable to method. method Swap() more interestingly, takes in the addresses of the local variables A and B. The Pointer variables var1 and var2 now point to A and B. so Method has access to the Memory that backs those two variables, so when it performs its switch, it writes into the memory of variables A and B.




Call by Reference ( & ):

while it is possible to achieve a call-by-reference manually by using the pointer operators, this approach is rather clumsy. First, it compels us to perform all Operations through pointers. second, it requires that we remember to pass the addresses (rather than the values) of the arguments when calling the Method.

Fortunately, in C#, it is possible to tell the compiler to automatically use call-by-reference rather than call-by-value for one or more parameters of a particular Method. We can accomplish this with a reference parameter. when we use a reference parameter, the address (not the value) of an argument is automatically passed to the Method. within the Method, operations on the reference parameter are automatically dereferenced, so there is no Need to use the pointer operators.

Let's have an simple example to understand, how we can pass arguments by reference to Method.


/*Example: Arguments passing to methods by Reference:
 InfoBrother:*/

using System;

namespace passingArguments
{
    class ByReference
    {
        //swapping Method:
        public void swap(ref int x, ref int y)
        {
            int temp = x;  //put value of x into temp:
            x = y;        //put value of y into x;
            y = temp;     //put value of temp into y:
        }

        //main method:
        static void Main(string[] args)
        {
            ByReference obj = new ByReference();  

            int a = 10;
            int b = 20;
            Console.WriteLine("Before swapping: a = {0}, b = {1}", a, b);

            obj.swap(ref a, ref b);  //Method call to swap the values:
            Console.WriteLine("After swapping: a = {0}, b = {1}", a, b);

            Console.ReadKey();
        }
    }
}


In The above example, the value of A and B change indirectly after swapping same like Pointers. As apparent from the Name "By Reference" we are not passing the value itself but some form of reference or address. Thus by passing the address of the variable to the called method, we convey to the Method that the number we should change is lying inside this passed Memory location, square it and put the result again inside that memory location. When the calling Method gets the control back after calling the called method, it gets the changed value back in the same Memory location.




Don't confuse about Pointer and Reference, Pointer is a variable which stores the address of another variable. while Reference is a variable which refers to another variable. Mostly Programmers Use References in Methods parameters and return type to define useful and self-documenting interfaces. and Use pointers to implement algorithms and data structures.



















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement