C# - Methods


Advertisements

Previous Page Next Page

A method also known as function is a block of statements which executes only when it is called somewhere in the program. A method provides re-usability of same code for different inputs, hence saves time and resources. There are some in-built methods in C# and one of the common method is Console.WriteLine() which is used to print the output in a new line. Users can also create their own method which is termed as user-defined methods.

Create method

In C#, a method must be declared in a class. Creating a method starts with modifier followed by return type of method. After that, it is followed by method's name and parenthesis containing method's parameter(s), if it has any. At last, it contains block of statements which is also called body of the method. Please see the syntax below:

Syntax


//Defining method
modifier return_type method_name(parameters)
  {
    statements;
  }

modifier: It defines the access type of the method and it is optional to use. There are four types of access modifier in cs.

  • public: accessible within all classes of application.
  • protected: accessible within the class in which it is defined and in its all sub-classes.
  • private: accessible only within the class in which it is defined.
  • default (without using any modifier): accessible within same class and package within which its class is defined.

return_type: A method can return value(s). The return_type is the data type of the value the method returns. If a method does not return anything in that case void is used as return_type.

Example: A method with no parameter

In the below example, a method called MyMethod is created to print Hello World!. The method requires no parameters to run and has no return type, hence void keyword is used.

static: tells the program that the MyMethod belongs to the MyClass and not an object of the MyClass.

using System;

namespace MyApplication { 
  class MyProgram {
    static void MyMethod() {
      Console.WriteLine("Hello World!."); 
    }   
    static void Main(string[] args) {
      MyMethod();
    }
  }
}

Output

Hello World!.

Call a method

After defining the method, it can be called anywhere in the program with it's name followed by parenthesis containing method's parameter(s), if it has any and semicolon (;). As in the above example, the method is called inside main() method using the following statement:

MyMethod();

Parameter

A parameter (or also known as argument) is a variable which is used to pass information inside a method. In above example, the method does not has any parameter. But a user can create a method with single or multiple parameters. Value of a parameter can be further used by the method to achieve desired result.

Example: A method with parameters

In the below example, the method called Mymethod is created which requires two integer numbers as parameters and print sum of two numbers in desired style. Please note that, the method returns nothing hence void is used as return type.

using System;

namespace MyApplication { 
  class MyProgram {
    static void MyMethod(int a, int b) {
      int sum;
      sum = a + b;
      Console.WriteLine("Sum of "+ a +" and "+ b +" is: "+ sum); 
    }   
    static void Main(string[] args) {
      MyMethod(15,10);
    }
  }
}

Output

Sum of 15 and 10 is: 25

Return Values

A method can be used to return values. To achieve this, user must have to define return type in definition and declaration of the method. In the below example, the return type is int.

using System;

namespace MyApplication { 
  class MyProgram {
    static int MyMethod(int a, int b) {
      return a + b;  
    }   
    static void Main(string[] args) {
      int x = 15, y = 10, sum;
      sum = MyMethod(x, y); 
      Console.WriteLine("Sum of "+ x +" and "+ y +" is: "+ sum); 
    }
  }
}

Output

Sum of 15 and 10 is: 25

Default Parameter Value

Default value can be assigned to a parameter at the time of creating method. When the method is called without parameter then it uses default value.

Example:

In the below example, default parameter value is used to perform sum operation on two, three and four integer numbers using same method called MyMethod. Here, default value is set while declaring the method.

using System;

namespace MyApplication { 
  class MyProgram {
    static int MyMethod(int p, int q, int r=0, int s=0) {
      return p+q+r+s;
    }  

    static void Main(string[] args) {
      int a = 15, b = 10, c = 5, d = 1;
      Console.WriteLine(MyMethod(a,b));
      Console.WriteLine(MyMethod(a,b,c)); 
      Console.WriteLine(MyMethod(a,b,c,d)); 
    }
  }
}

Output

25
30
31

Named Argument

In C#, the arguments can be passed in key: value pairs.

Example:

In the below example, arguments can be passed in key: value pairs and hence order of arguments does not matter while using this method.

using System;

namespace MyApplication { 
  class MyProgram {
    static int MyMethod(int p, int q) {
      return p/q;
    }  

    static void Main(string[] args) {
      int a = 10, b = 2;
      Console.WriteLine(MyMethod(q:b, p:a));
    }
  }
}

Output

5

Recursive method

A method which can call itself is known as recursive method. A recursive method generally ends with one or more boundary conditions.

Example:

A method for calculating factorial using recursion method is described below.

using System;

namespace MyApplication { 
  class MyProgram {
    static int factorial(int x) {
      if(x==0)
        {return 1;}
      else
        {return x*factorial(x-1);} 
    }   
    static void Main(string[] args) {
      Console.WriteLine(factorial(3)); 
      Console.WriteLine(factorial(5)); 
    }
  }
}

Output

6
120





Previous Page Next Page