Tuesday, March 23, 2010

Passing Parameters to Methods

In C#, there are two ways to pass a parameter to a method: by value (which is the default) or by reference. Passing parameters by reference makes the changes to the variable values persist. To pass a parameter by reference, modify the parameter with the ref keyword.
The following example demonstrates swapping the values of two variables.
//Example 6-4.cs
//Swap method example – successful trial
using System;
class MyClass
{
    static void Swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
    static void Main()
    {
        int x = 25;
        int y = 33;
        Console.WriteLine(“Before swapping: x ={0}, y = {1}”, x,y);
        Swap(ref x, ref y);
        Console.WriteLine(“After swapping: x = {0}, y = {1}” , x, y);
       
    }
}
As we can see in the preceding example, the Swap method is using the ref keyword to modify the parameters in both the method header and the method call. This method did swap the two variables, as in indicated in the output.
In the following example, take a look at how this function will behave if we pass the parameters by value – without the keyword ref.
//Example 6-5.cs
//Swap method example – unsuccessful trial
using System;
class MyClass
{
    static void Swap(int x, int y)
    {
        int temp = x;
        x = y;
        y = temp;
        Console.WriteLine(“Values inside the method: x = {0} , y = {1}” , x ,y);
    }
    static void Main()
    {
        int x = 25;
        int y = 33;
        Console.WriteLine(“Before swapping : x = {0}, y = {1}”, x, y);
        Swap(x,y);
        Console.WriteLine(“After swapping: x={0}, y = {1}”, x, y);
    }
}
As we can see in the output, the values of x and y did not change after invoking the Swap method. The change took place only inside the method, but when the method returned to the caller, the values were the same.

No comments:

Post a Comment