Article

Methods


Methods

method is a series of statements that together perform a task. In C# program we have at least one class with a method named Main. methods do only one specific task that is good for programming. Right use of methods get the following advantages:

  • duplication of code reduce
  • clarity of the code get improving
  • code reuse
  • hiding information
  • Decomposing complex problems into simpler ways

Defining Methods

Method is followed by parentheses() & it is defined with the name of the method. There are some pre-defined methods in C#, which you already know about Main(), but to perform certain action you can also create your own methods.

There are various elements of a method −

  • Modifier:This tells the visibility of a variable or a method from another class.for e.g Public, Protected, Private are access modifiers.
  • Method name:It tells the name of the user defined method by which the user calls it or refer it. E.g. MethodName().it is case sensitive.
  • Method body:This contains the set of instructions i.e block of code which is needed to complete the required activity.
  • Parameter list:This is enclosed in parenthesis.list of input parameters are defined by their data type and separated by comma. parameters are optional,if there are no parameters then empty parentheses used for methods.
  • Return type: return type means method return value.methods may be have return value or not. if method not return any value then the return type is void.

 
using System;

namespace MyCode
{
  class Program
  {
    static void MethodName()
    {
      Console.WriteLine("This is Declaration of Method");    //Declaration of method
    }

    static void Main(string[] args)
    {
      MethodName();
    }
  }
}
 
 

  
 OUTPUT
 This is Declaration of Method
 
  

Calling Methods

calling a method means write the method name with parentheses() and semicolon ; In the example we call method i.e. MethodName();    when we call a method then these functionality happen:

  • all the statements of method is complete
  • if there is return statement then it give return value
  • if there is error then it throw an exception

 
using System;

namespace MyCode
{
  class Program
  {
    static void MethodName()
    {
      Console.WriteLine("This is Declaration of Method");   
    }

    static void Main(string[] args)
    {
      MethodName();  //calling method
    }
  }
}
 
 

  
 OUTPUT
 This is Declaration of Method