In this article i am explaining about Method in C#. Method is the production block of object-oriented programming. It combines related code together and makes program easier. In C# method declaration, you can declare method by following way:

Syntax:

<Access Specifier> <Return Type> <Method Name>(Parameter list)
{
    Body
}

Example:
public void Hello()
{
      Body
}
In the above example, the public is an access specifier,  void  is a return data type that return nothing and Hello() is a method name. There is no parameter define in Hello() method.If the function returns interger value, then you can define function as follow :

public int Add()
{
      Body
      return integer value
}
If the function is returning string value, then you can define function as follow:
public string PrintName()
{
      Body
      return string value
}
You always remember, whenever use return data type with method, must return value using return keyword from body. If you don’t use return any value, then you can use void data type.
namespace Declaring_Method
{
  class Program
   {
     string name, city;
     int age;
     // Creating method for accepting details
     public void AcceptDetails()
      {
        Console.Write("\nEnter your name:\t");
        name = Console.ReadLine();
        Console.Write("\nEnter Your City:\t");
        city = Console.ReadLine();
        Console.Write("\nEnter your age:\t\t");
        age = Convert.ToInt32(Console.ReadLine());
      }
     // Creating method for printing details
     public void PrintDetails()
      {
        Console.Write("\n\n===================");
        Console.Write("\nName:\t" + name);
        Console.Write("\nCity:\t" + city);
        Console.Write("\nAge:\t" + age);

        Console.Write("\n===================\n");
      }
     static void Main(string[] args)
      {
        Program p = new Program();
        p.AcceptDetails();
        p.PrintDetails();
        Console.ReadLine();
      }
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *