HOME RESOURCES PLACEMENTS CONTACT FEEDBACK SUBSCRIBE
QUICK LINKS .NET Articles
.NET Training Tutorial
HR Interview Questions
.NET Interview Questions
SQL Interview Questions
JAVA Interview Questions

Methods in C#
In C# functions are called as methods. Methods are reusable code blocks, to which you can optionally pass parameters. Method does some processing and can optionally return a value. We define our method once, and call it any where with in our application any number of times. The complete syntax of a method declaration is shown below. Attributes and parameters are optional in a method declaration. We will discuss about attributes and modifiers in our later article.

    attributes modifiers return-type method-name(parameters )
    {
        statements
    }

Let us look at example of a method. We have a simple method CalculateArea() to which we pass the radius. The method will calculate the area of the circle and return the value. The type of the value returned by the method id double. The type of the value the method expects as parameter is int. In this example we have
  • 2 classes MethodsDemo class and a Circle class.
  • In the Main method we first create an instance(C1) of the Circle class.
  • To invoke the CalculateArea() method, we qualify it with the C1 instance. As we are using an instance of a class to invoke the method, this type of a method is called instance method.
  • In general we have 2 types of methods.
    • Static Methods
    • Instance Methods(Also called as non static methods)

using System;

class MethodsDemo

{

    public static void Main()

    {

        int CircleRadius = 10;

        //We call and reuse CalculateArea() method

        Circle C1 = new Circle();

        double CircleArea = C1.CalculateArea(CircleRadius);

        Console.WriteLine("The area of the Circle is " + CircleArea);

    }

}

                                                             

class Circle

{

    //A reusable method to calculate area of a circle

    //by passing Radius as the parameter

    public double CalculateArea(int Radius)

    {

        double Area = 3.14 * Radius * Radius;

        return Area;

    }

}

An example: How to declare and use a static method in C#
In the example below
  • CalculateArea() is a static method as it has static modifier in the method declaration.
  • In the Main method we invoke CalculateArea() Method. We invoked this method by qualifying it on the name of the class and not on an instance of the class.

using System;

class MethodsDemo

{

    public static void Main()

    {

        int CircleRadius = 10;

        //To invoke a static method you prefix the method name with the name

        //of the class containing the method, not the instance of the class

        double CircleArea = Circle.CalculateArea(CircleRadius);

        Console.WriteLine("The area of the Circle is " + CircleArea);

    }

}

                                                   

class Circle

{

    //This is a static method as it has static modifier

    //in the method declaration

    public static double CalculateArea(int Radius)

    {

        double Area = 3.14 * Radius * Radius;

        return Area;

    }

}

Differences between static methods and instance methods
  • When a method declaration includes a static modifier, that method is said to be a static method. When no static modifier is present, the method is said to be an instance method.
  • A static method cannot be invoked on an instance of a class. It is a compile-time error to invoke a static method on an instance of a class.
  • A static method cannot be invoked on an instance of a class. It is a compile-time error to invoke a static method on an instance of a class.
Different types of Method parameters in C#
In C# we have 4 different types of parameters that we can pass to a method as listed below
  • Value Parameters
  • Reference Parameters
  • Output Parameters
  • Parameter arrays
The syntax for parameters in C# is as shown below
[modifiers] DataType ParameterName 
[modifiers] are optional and can have one of the following values
  • ref
  • out
  • params
If the parameter that we are passing doesnot have any modifier, then the parameter is a value parameter by default.
Examples for different parameter types that we can pass to a method in C#
1. Passing parameters by value to a method

using System;

class ValueParametersDemo

{

    // x and y are value parameters as they do not have any modifiers

    static void Swap(int x,int y)

    {

        int temp = x;

        x = y;

        y = temp;

    }

    public static void Main()

    {

        int x = 1, y = 2;

        //As we are passing parameters by value swap method will have

        //its own copy of variables and hence i and j values

        //are not swapped in the output

        Swap(x, y);

        Console.WriteLine("x = {0}, y = {1}", x, y);

    }

}

  • In the above example swap() method swaps value of x to y. In the above example x and y are value parameters as they donot have any modifiers like ref, out or params.
  • We are passing values of 1 and 2 to the swap method. The output is "x = 1, y = 2". Swapping did not happen.
  • This is because we are passing x and y as value parameters to the Swap () method. When we pass parameters as value type parameters, the swap method will have its own copy of the variables and hence the x and y values are not swapped.
  • For this example to work correctly we have to pass parameters as reference type parameters as shown in the below example.
Note: A parameter declared with no modifiers is a value parameter. A value parameter corresponds to a local variable that gets its initial value from the corresponding argument supplied in the method invocation. A method can assign new values to a value parameter. Such assignments only affect the local storage location represented by the value parameter. They have no effect on the actual argument given in the method invocation.
2. Passing reference parameters to a method

using System;

class ReferenceParametersDemo

{

    // x and y are reference parameters as they have ref modifier

    static void Swap(ref int x,ref int y)

    {

        int temp = x;

        x = y;

        y = temp;

    }

    public static void Main()

    {

        int x = 1, y = 2;

        //As we are passing parameters by reference the original

        //arguments x and y will be swapped. The out put is

        //x=2, y=1

        Swap(ref x,ref y);

        Console.WriteLine("x = {0}, y = {1}", x, y);

    }

}

In the above example
  • A parameter declared with a ref modifier is a reference parameter. Hence in the above example x and y are reference parameters.
  • In the main method we have another set of 2 local variables x=1 and y=2. We are passing x and y with the ref modifier to the swap method. Unlike a value parameters, reference parameters does not create a new storage location. Instead, reference parameters represent the same storage location as the variable given as the argument in the method invocation.
  • As the swap method operates on the storage locations of the arguments passed, the variables get swapped.
3. Output Parameters

using System;

class OutputParametersDemo

{

   

    static void ProcessDetails(int ID,out string Name,out int Age)

    {

        Name = "Parsad";

        Age = 25;

    }

    public static void Main()

    {

        string NameofPerson;

        int AgeofPerson;

        ProcessDetails(10, out NameofPerson, out AgeofPerson);

        Console.WriteLine("Name = {0}, Age = {1}", NameofPerson, AgeofPerson);

    }

}

In the example above
  • A method can have only one return type(int,string,object etc...) or no return type(void). If you want the method to return data of multiple types that is when out parameters are extremly useful.Output parameters are typically used in methods that produce multiple return values.
  • For example to a method I pass person ID and the method should return Name and age of the person. Name is of string data type and Age is of integer data type. Our method cannot return both string and int data type at the same time. So we can make use of out parameters.
  • A parameter declared with an out modifier is an output parameter. In our example Name and age are output parameters as they have out modifier.
  • In the Main method we have 2 local variables NameofPerson and AgeofPerson. When we invoke ProcessDetails() method we pass these local variables to the method with an out modifier. The values "Parsad" and "25" are copied into NameofPerson and AgeofPerson variables respectively which are then written to the console.
4. Parameter Arrays

using System;

class ParameterArraysDemo

{

    //This method defines Names parameter array

    static void ProcessArray(params string[] Names)

    {

        Console.WriteLine("Numbers of names in the Array = "+ Names.Length);

        foreach (string Name in Names)

        {

            Console.WriteLine(Name);

        }

    }

    public static void Main()

    {

        string[] PersonNames = { "Prasad","Giri","Madhu"};

        //We invoke the above method by passing a string array with 3 names in it.

        ProcessArray(PersonNames);

    }

}

In the example above
  • A parameter declared with a params modifier is a parameter array. In our example Names is a parameter array.
  • In the Main method we have string array PersonNames. We invoke ProcessArray() method by passing PersonNames as a parameter array.
Key points to remember about parameter array
  • If a formal parameter list includes a parameter array, it must be the last parameter in the list and it must be of a single-dimensional array type.
  • It is not possible to combine the params modifier with the modifiers ref and out

Njoy Programming
   ByPrasad Cherukuri