06 - C# Methods

6.1 Method Structure

A method consists of one or more programs statements which can be created by calling the method name. The code in the complex application becomes flexible and easy to maintain with the use of methods. Repetitive tasks can be easily performed by getting the specific records and text. The code can be reused easily in a method. 

To use the method, user needs to:

1) Define methods

2) Call methods

1) Define methods: Defining a method means declaring the elements of its structure. The following syntax can be used to define a method:

<Access specifier><Return Type><Method Name>(Parameter List)
{
    Method Body
}

In the syntax mentioned above, the elements in the method are as follows:

  • Access specifier: It determines the access level of variables or method from another class.
  • Return Type: A method can return a value of another type. The void return type is used when a method does not return any value.
  • Method Name: The method name and the variable name must be different or any other item mentioned in the class.
  • Parameter List: It is used to send and receive the data from a method. It is included between the parentheses after the method name.
  • Method Name: It is a set of instructions that perform a specific task.

A code sample for the methods in C# is as shown below:

class Calculate1
{
    public int AddNumber ( int no1, int no2)
    {
        int result;
        result = no1+no2;
        return result;
    }
}

In the code snippet, the public access specifier states that the method can be accessed from outside the class. The method returns the integer type value. AddNumber is the name of the method. The method is accepting two integer values and returning the stored value in the result variable.

2) Call methods: After defining the method, you can call it by using the name of the method. The method name is followed by parentheses even if the method call has no parameters. The declaration of method is as shown below:

The code to call methods is as shown below:

class Program
{
    public int AddNumber ( int no1, int no2)
    {
        int result;
        result = no1+no2;
        return result;
    }
    static void Main ( string[ ] args)
    {
        Program p = new Program();
        int value = p.AddNumber(2,4);
        Console.WriteLine(“the result of numbers is:”+value);
        Console.Read();
    }
}

The output is as shown below:

In the above example, the program begins with Main() method of the Program class. An object p is created to access the method of the class. The parameters 2 and 4 are passed to the method.

6.2 Static and Instance methods

Static methods are invoked directly from the class level without creating an object. The main() method is the static method in C#. Static methods do not have instances. They are called with type name, not by identifier. They can be public or private. To call a static method, we use the name of the class and the dot operator.

A code sample to demonstrate the static method is as shown below:

class Program
{
    static void A()
    {
        Console.WriteLine(“First Static method”);
    }
    static int B()
    {
        Console.WriteLine(“Second Static method”);
        return 1;
    }
    static void Main ( string[ ] args )
    {
        Program.A();
        Program.B();
        Console.Read();
    }
}

The output is as shown below:

The instance methods in a class make use of public or private static data that belongs to the class. The object of the class is created. User can access methods using the object of the class. Add the method name preceding the dot operator in the declaration.

A code sample to demonstrate the Instance methods is as shown below:

class Program
{
    void C()
    {
        Console.WriteLine(“First Instance method”);
    }
    void D()
    {
        Console.WriteLine(“Second Instance method”);
    }
    static void Main( string[ ] args )
    {
        Program p = new Program();
        p.C();
        p.D();
        Console.Read();
    }
}

The output for the code is as shown below:

6.3 Using Methods with Parameters

When user defines a method, the list of parameters can be added in the parentheses followed by the method name. Each parameter has a name and a type. The syntax of parameter is similar to the declaration of the local variables.

The following code snippet is used to show a method with two parameters.


   void MethodwithParameters( int x, int y )
   {
   }

 

In the preceding code snippet, the method MethodwithParameters() with two parameters x and y is declared.

Parameters can be passed using the three mechanisms:

1) Value: They are referred as ‘Input Parameters’ as the data can be passed to the method but it cannot be returned. The changes added to the method cannot be reflected outside the method.

2) Reference: They are referred as Input/Output parameters as the data can be passed to the method and returned by it. The changes made to the method are reflected outside the method.

3) Output: They are refereed as Output parameters as the data can be extracted from the method. Any changes made to the method are reflected outside the method. They are declared by using out keyword specified before the parameter type and name.

Passing parameters by value:

Passing parameters by value is the default type for passing parameters to the method. The value parameter is defined by specifying the data type followed by the variable name. The values in the variable are passed when the method is invoked. The data type of the parameters passed must match the parameters data type in the method declaration.  

The following statement is used to define the syntax used to declare a value parameter.

    <return type>MethodName ( <data type> variable name )
    {
    }

 

 

A code sample to demonstrate the example of pass by value is shown below:

class IncrementData
{
    void AddOne(int i)
    {
        i++;
    }
    static void Main( string[ ] args )
    {
        IncrementData d = new IncrementData();
        int no = 3;
        d.AddOne(no);
        Console.WriteLine(“The new number is:”+no);
        Console.Read();
    }
}

The output for the code is as shown below:

Passing parameters by reference:

A reference parameter is the reference to the memory location of a parameter. In reference parameter new storage location is not created. It stores the value in the same memory location as the variable passed in the memory call. 

The declaration of the reference parameter is done by using the ref keyword. The example for the reference parameters is as shown below:

void ShowReference( ref int Id, ref int age )
{

}

A code sample to demonstrate the pass by reference method is as shown below:

class IncrementData
{
    void AddOne( ref int i)
    {
        i++;
    }
    static void Main ( string[ ] args )
    {
        IncrementData d = new IncrementData();
        int no = 3;
        d.AddOne ( ref no );
        Console.WriteLine(“The new number is:”+no);
        Console.Read();
    }
}

The output for the code is as shown below:

Passing parameters by Output:

A return statement is used for returning a value from the method. A return statement can be used to return only a single value. The output parameter is used to overcome this problem.

Output parameters are like reference parameters but they transfer data out of the method. An output parameter is reference to the storage location supplied by the caller. To declare an output parameter, the out keyword is used before the data type and the variable name. 

A code sample to demonstrate the output parameter is as shown below:

class OutDemo
{
    static void OutSample( out int i )
    {
        i=20;
    }
    static void Main ( string [ ] args )
    {
        int no;
        OutSample( out no );
        Console.WriteLine(“Value for the number is:”+no );
        Console.Read();
    }
}

The output for the code is as shown below;

6.4 this reference

The this keyword is used to refer to the current instance of the class. It can be used to access members from within the constructors and instance methods. The naming conflicts can be eliminated using this reference. They cannot be used as reference to a static field or method. It cannot occur inside a static class.

A code sample to demonstrate the use of this reference is as shown below:

class OutDemo
{
    int I;
    public OutDemo()
    {
        this.Decrease();
    }
    public void Decrease()
    {
        i--;
        this.i--;
        Console.WriteLine(“The value of I is”+i);
    }
    static void Main (string [ ] args)
    {
        OutDemo o = new OutDemo();
        o.Decrease();
        Console.Read();
    }
}

 

The output for the code is as shown below:

Like us on Facebook