Tuesday, March 23, 2010

Various Ways to Pass Parameters to Methods

There is more than one way to pass parameters to a method by reference. There are three parameter modifiers, each of which results in saving the changes of the variable values after the method returns to the caller. The three modifiers are:
•    ref
•    out
•    params
•    ref: -
As we have seen in the preceding examples, the ref keyword is used to pass variables to a method and reflect back the changes that occurred on the original variables. When we use ref to pass a variable to a method, the variable must be initialized first; otherwise, we will get a compiler error. For example:
string myVariable = “This my string”;    //initialize the variable
MyMethod(ref myVariable);        //invoke the method

When the method returns the variable, myVariable will retain the changes that occurred to it in MyMethod.

•    out: - The out keyword does the same work as the ref keyword when used as a parameter modifier. It does not require initializing the variable before passing it to the method, but it does require initializing the variable in the method itself. For example, the method might look something like this:
    void MyMethod(out string myVariable)
    {
        myVariable = “This is my string”;
    }
In order to call this method, use the out keyword:
    MyMethod(out myVariable);
The variable myVariable might not be initialized at all. It will be assigned the vale “This is my string” when the method returns to the caller. Notice that the out keyword is used in both the method header and the call.
It is possible to use more than one parameter, as in this example:
void YourMethod(out int x, out int y, out int z)
{

}
This method is called in the same way:
YourMethod(out m, out n, out l);
Note: - It is not enough to have different parameter modifiers in order to overload a method. Methods must also be different in the type of parameters they use.
In the following example, the out keyword is used to pass an uninitialized array to the method MyMethod. When the method returns to Main, its elements are initialized.
//Example 6-6.cs
//Out Example
using System;
public class MyClass
{
    public static void MyMethod(out int[] myList)
    {
        myList = new int[] {1945, 1966, 1987, 1997}; // initialize the array
    }
    public static void Main()
    {
        int [] myarray; //declare an uninitialized array
        MyMethod(out myarray); //pass it as a parameter

        //Display the array:
        for ( int i = 0; i < myarray.Length; i++)
            Console.Write(“{0} “, myarray[i]);
    }
}
Notice in the example above that MyMethod was declared static in order to be called directly without the need to create an object.
•    params: -The keyword params is used with arrays. It lets we pass any number of parameters to a method without the need to declare them in an array. This keyword is required only in the method declaration. For example, the method:
    static void MyMethod(params object[] myObjArray)
              Can be called like this:
    MyMethod(123,’A’, “My original string”);
The parameters passed in this call are all of the type object, which means they can include any types descended from the object class.
Consider also the following method:
static void MyMethod(params int[] myIntArray)
This method can be called by passing a group of integers that constitute an integer array regardless of its length, for example:
MyMethod(2,4,7);
Any method that uses the params keyword cannot use more than one parameter.
In the following example, the use of the params keyword in the declaration of the method is demonstrated. It also demonstrates the overloading of two methods with the same name and different parameters. One method uses an object array and the second method uses an integer array.  Both methods change the content of the array passed to it. The content of each array is displayed before and after the change takes inside the method.
//Example6-7.cs
//params and overloading example
using System;
public class MyClass
{
    //Declare MyMethod that uses integer parameters:
    public void MyMethod(params int[] myIntArray)
    {
        //Display the integer array before the change:
        Console.WriteLine(“My original integer list:”);
        for(int i = 0; I < myIntArray.Length; i++)
        {
            Console.WriteLine(myIntArray[i]);
        Console.WriteLine();

        //Changing the second array element:
        myIntArray[1] = 555;
        //Display the integer array after the change:
        Console.WriteLine(“My integer list after the change:”);
        for(int i = 0 ; i < myIntArray.Length; i++)
            Console.WriteLine(myIntArray[i]);
        Console.WriteLine();
        }
    //Declare MyMethod that uses object parameters:
    public void MyMethod(params object[] myObjArray)
    {
        //Display the object array before the change:
        Console.WriteLine(“My original object list:”);
        for(int i =0; i < myObjArray.Length; i++)
            Console.WriteLine(myObjArray[i]);
        Console.WriteLine();
        //Changing the third array element:
        myObjArray[2] = “My new string”;
        //Display the results after the change:
        Console.WriteLine(“My object list after the change:”);
        for(int i = 0; i < myObjArray.Length; i++)
            Console.WriteLine(myObjArray[i]);
        Console.WriteLine();
    }
}
class MainClass
{
    static void Main()
    {
        //Declare an object array:
        object[]  myObjList = new object[] {123,’A’, “My old string”};
        MyClass mc = new MyClass();
        //Pass four integers to the “first” MyMethod:
        mc.MyMethod(11,22,33,44);    //using numeric parameters
        //Pass an object array to “second” MyMethod:
        mc.MyMethod(myObjList);    //using an object array
    }
}

No comments:

Post a Comment