Tuesday, November 3, 2009

METHODS




A method is a member that implements a computation or action that can be performed by an object or class. Static methods are accessed through the class. Instance methods are accessed through instances of the class.
Methods have a (possibly empty) list of parameters, which represent values or variable references passed to the method, and a return type, which specifies the type of the value computed and returned by the method. A method’s return type is void if it does not return a value.
The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.

Parameters

Parameters are used to pass values or variable references to methods. The parameters of a method get their actual values from the arguments that are specified when the method is invoked. There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.

Value and Reference Parameters
  You pass value-type method parameters by value—that is, you pass a copy of the value to the method. Therefore, what the called method does with the incoming parameter doesn’t affect the variable passed down from the calling method. Consider the following simple example:
Using System;
class SomeClass
{
    public int ChangeInt(int val)
    {   val = val*2;
        return val;
    }
}

class ValRefTest
{
    static void Main(string[] args)
    {
        SomeClass sc = new SomeClass();
        int val1 = 3;
        int val2 = sc.ChangeInt(val1);
        Console.WriteLine("val1 = {0}, val2 = {1}", 
            val1, val2);
    }
}
The output from this code will be:
val1 = 3, val2 = 6
The behavior with reference-type parameters is different because what gets passed is a copy of the reference (another reference to the same data). Therefore, if the called method makes changes to the data through the reference, the changes are made to the original data. The reference held by the calling method is a reference to the same data, so the changes will be available to the calling method when the called method returns:
Using System;
class SomeClass
{
    public int ChangeInt(ref int val)
    {   val = val*2;
        return val;
    }
}

class ValRefTest
{
    static void Main(string[] args)
    {
        SomeClass sc = new SomeClass();
        int val1 = 3;
        int val2 = sc.ChangeInt(ref val1);
        Console.WriteLine("val1 = {0}, val2 = {1}", 
            val1, val2);
    }
}
The output from this code will be:
val1 = 6, val2 = 6
Let’s be clear about this process: in both cases, a copy of the parameter passes from caller to called method. If you pass a copy of a value type, you get a copy of the data. But if you pass a copy of a reference type, you get a copy of the reference. When accessing the original data, a copy of a reference is indistinguishable from the original reference.
Using out Access to Parameters
The return type enables you to send back a single variable from a method; however, sometimes you will want more than one value to be returned. Although reference variables could be used to do this, C# has also added a special attribute type specifically for returning data from a method.
You can add parameters to your method header specifically for returning values by adding the out keyword. This keyword signifies that a value is being returned out of the method but is not coming in. When you call a method that has an out parameter, you must be sure to include a variable to hold the value being returned.
using System;

 class nbr
 {
 public void math_routines( double x, out double half, out double squared,
            out double cubed )
            {
                        half = x / 2;
                        squared = x * x;
 cubed = x * x * x;
 }
 }

 class Outter
 {
            public static void Main()
 {
                        nbr doit = new nbr();

                        double nbr = 600;
 double Half_nbr, Squared_nbr Cubed_nbr;
           
 doit.math_routines( nbr, out Half_nbr,
 out Squared_nbr, out Cubed_nbr );
                        Console.WriteLine(“After method -> nbr = {0}”, nbr);
 Console.WriteLine(“ Half_nbr = {0}”, Half_nbr);
 Console.WriteLine(“ Squared_nbr = {0}”, Squared_nbr);
 Console.WriteLine(“ Cubed_nbr = {0}”, Cubed_nbr);
 }
 }
Output of the program is-
After method -> nbr = 600
Half_nbr = 300
Squared_nbr = 360000
Cubed_nbr = 216000000

Variable Number of parameters
A parameter array permits a variable number of arguments to be passed to a method. A parameter array is declared with the params modifier. Only the last parameter of a method can be a parameter array, and the type of a parameter array must be a single-dimensional array type.
The Write and WriteLine methods of the System.Console class are good examples of parameter array usage. They are declared as follows.
public class Console
{
            public static void Write(string fmt, params object[] args) {...}
            public static void WriteLine(string fmt, params object[] args) {...}
            ...
}
Within a method that uses a parameter array, the parameter array behaves exactly like a regular parameter of an array type. However, in an invocation of a method with a parameter array, it is possible to pass either a single argument of the parameter array type or any number of arguments of the element type of the parameter array. In the latter case, an array instance is automatically created and initialized with the given arguments. This example
Console.WriteLine("x={0} y={1} z={2}", x, y, z);
is equivalent to writing the following.
object[] args = new object[3];
args[0] = x;
args[1] = y;
args[2] = z;
Console.WriteLine("x={0} y={1} z={2}", args);
For instance, the example
using System;
class Test
 {
 static void F(params int[] args) {
 Console.WriteLine("# of arguments: {0}", args.Length);
 for (int i = 0; i < args.Length; i++)
 Console.WriteLine("\targs[{0}] = {1}", i, args[i]);
 }
 static void Main() {
 F();
 F(1);
 F(1, 2);
 F(1, 2, 3);
 F(new int[] {1, 2, 3, 4});
 }
 }
 shows a method F that takes a variable number of int arguments, and several invocations of this method.
 The output is:
 # of arguments: 0
 # of arguments: 1
 args[0] = 1
 # of arguments: 2
 args[0] = 1
 args[1] = 2
 # of arguments: 3
 args[0] = 1
 args[1] = 2
 args[2] = 3
 # of arguments: 4
 args[0] = 1
 args[1] = 2
 args[2] = 3
 args[3] = 4