Saturday 24 May 2014

Methods in C Sharp

In OOP Language, Objects are used as building  blocks in developing a program. They are run-time entities . They may present a person , a place or table of data.. etc.

Objects encapsulate data, and code to manipulate that data. The code designed to work on the data is know as methods in C# .

C# is pure object oriented language and therefore, every method must be contained within a class. 

DECLARING METHODS

 modifier type method-name (formal- parameter- list)
{
         method body 
}

Method declaration has five parts:
  • Name of the method
  • Type of value the  method returs (type)
  • List of parameter ( formal parameter list)
  •  Body of the method
  • Method modifiers (modifier)

THE MAIN METHOD:

C#  start execution at a method named Main( ). This method must be the static method of a class and must have either int or void as return type

                  public static int Main() 
                             or
                  public static void Main () 

The modifier public is used as the method must be called from outside the program. The Main  can also have parameters which may receive values from the command line at the time of execution.
                public static int Main (string [] args )
                           or
               public static void Main (string [] args)


INVOKING METHODS:



Once method have been define, they must be activated for operations. The process of activating a method is know as invoking or calling. The invoking is done using dot operator as below

            objectname.methodname (parameter);

Defining and invoking  method

using system;
Class FirstMethod 
{
      //define method
      int Cube( int x)
           {
                        return (x*x*x);
            }
}

Class MethodTest
{
  
      public static void Main()
       {
            //create the object of the class
              Method M = new Method();
            
          //Invoke the cube method
            int y= M.Cube(10);

          Console.Writeline ( y) ;
      
       }

}

Output: 1000

Calling a Static Method:


using system;
Class StaticMethod
{
       public static void Main()
       {
               double y = Square(2);    //calling method
                Console.Writeline(y); 

       }

       static int Square(int x) //Method definition 
       {
                   return (x * x);
         }
}

NESTING OF METHODS:

A Method can be called using only its name by another method of the same class. This is known asnesting of methods.

using system;

class Nesting
{
void Largest ( int m, int n)
           {
                int large=Max (m, n)                 // Nesting Method
                 console.writeline(large);
           }

           int Max( int a , int b)
         {
              int x=(a >b) ? a : b;
               return (x);
         }
}

class NestTesting
{
            public static void Main()
            {
                 Nesting next= new Nesting();
                 next.large(90, 75);                     // Method Call
             }
}

METHOD PARAMETERS

A method invocation creates a copy, specific to that invocation, of the formal parameters and local variables of that method. The actual argument list of the invocation assign values or variables references to the newly created formal parameters. within the body of a method, formal parameters can be used like any other variables.

The invocation involves not only passing the values into the method but also getting back the results from the method. For managing the purpose of passing values and getting back the results, C# have four kinds of parameters.


  1. Value parameters
  2. Reference parameters
  3. Output parameters
  4. Parameter arrays

Value parameters:

By default,  method parameters are passed by value. That is, a parameter declared with no modifier is passed by value and is called a value parameter. When a method is invoked, the values of actual parameters are assigned to the corresponding formal parameters. The values of the value parameters cab be changed within the method. The value of the actual parameter that is passed by value to a  method is not changed by any changes made to the corresponding formal parameter within the body of the method. This is because the methods refer to only copies of those variables when they are passed by value.

  using System;
 Class PassByValue
{
    static void Change (int n)
    {

             n= n+100;  //   value of n is changed here

     }

   public static void Main()
   {
         int  x=10;
          
        Change(x);
       
        Console.Writeline("value of x is:" + x);
  
   }

}

The value of x will produce the output is :  10

When method Change() in invoked, the value of x is assigned to n and a new location for n is created in the memory. Therefore, any change in n does not affect the value stored in the location of x

Reference parameters:

We can, however, force the value parameters to be passed by reference. To do this, we use he ref keyword. A parameter declared with the ref modifier parameter. 
                                
                               void Modify ( ref int y)

Unlike the value parameter, a reference parameter does not create a new storage location. Instead, it represents the same storage location as the actual parameter used in the method invocation.  Imporant point to consider here that: when we declare variable in reference type then make it sure that  corresponding argument in the method invocation must also be declared as ref .

OUTPUT PARAMETERS

Output parameter are used to pass results back to the calling method. This is achieved by declaring the parameters with an out keyword. Similar to a reference parameter, an output parameter does not create a new storage location. Instead, it becomes an alias to the parameter in the calling method. When a formal parameter is declared as out, the corresponding actual paramete in the calling method must also be declared as out.

using System;
class Output
{
   static void Sqaure ( int x, out int y )
  {
            y= x * x;

   }

   public static void Main ()
   {
         int m; // no need to initialized
        Sqaure ( 10, out m);
         Console.WriteLine("m=" + m);

   }

}

WHAT IS METHOD OVERLOADING:

C# allows us to create more than one method with the same name, but with the different parameter lists and different definitions. This is called method overloading. Method overloading is used when methods are required to perform similar tasks but using different input parameters.

Overloaded methods must differ in  number and or type of parameters they take. This enables the compiler to decide which one of the definitions to execute depending on the type and number of arguments in the method call. Note hat the  method's return type does not play any role in the overload resolution.

// Method definition

int Add ( int a, int b) {..... }

int Add ( int a , int b, int c) { ....}

double Add ( float x, float y} { ....}

double Add ( int x, float y) { ...} 

//Method calling

int m = Add ( 10,23) ;

int m =  Add (10,23,34) ;

double x = Add (1.0 F, 3.0 F) ;

The method selection involves the following steps:

  1. The compiler tries to find an exact match in which the types of actual parameters are the same and uses that method.
  2. If the exact match is not found, then the compiler tries to use the implicit conversions to the actual arguments and then uses the method whose match is unique. If the conversion creates multiple matches, then the compiler will generate an error message

No comments:

Post a Comment

stats counter
your visitor number