Topic : Methods | Function in C# Programming: Defining method | Calling Method | Recursive Methods

What is method?

A Method is a group of statements that perform some task together. Method receive some information, do some process and provide a result. Method break large computing tasks into smaller ones, and enable people to build on what others have done instead of starting over form scratch. Every C# Program has at least one class with a method named Main , and all the most trivial Program can define additional functions.

Actually We are dividing our code into small and separate Modules known as Methods. This strategy allows us to think of the programming task more abstractly. Creating modules makes it easier to work with programs, allows several programmers to write or modify modules in the same programs, and enables us to create reusable programs pieces.



function : infobrother

Concept:

In above chair it has a seat back and four legs. Now we need to make a seat, back and four legs out of wood. the major task is to make chair, sub tasks are, make a seat its back and then fabricate four legs. The legs should be identical. We can fashion one leg and then re-using this prototype, we have to build three more identical legs. The last task is to assemble all these to make a chair. We have a slightly difficult task and have broken down it into simpler pieces. This is the concept of functional design or top-down designing.

When we write a Method, it must start with a name, parentheses, and surrounding braces just like with main(). Methods are very important in code reusing.

There are two types of Methods:



  • » Function that return a value.
    » Function that do not return a value.



Suppose, we have a Method that calculate the sum of two numbers such that Method will return the sum of Numbers. similarly we may have a Method which displays some information on the screen so this Method is not supposed to return any value to the calling program.





Defining Methods:

A Method Definition tells the compiler about a Method's name, return type, and parameters. The actual body of the Method can be defined separately.
In C#, every Method has a header, or Function Definition, that includes five parts:



	

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



  • Access Specifier:

    Access Specifier describes as the scope of Accessibility of an Object and its members. All C# Types and type members have an accessibility level. we can control the scope of the member object of a class using access specifiers. C# Provide five access specifiers, they are: Public , Private and Protected.


    Return Type:

    Return type specifies the output type of a function. The output type can be number or text. the return type is the data type of the value the method returns. if the method is not returning any values, then the return type is void.


    Method Name:

    Method name is a Unique identifier. it is a case sensitive so "Infobrother" and "InfoBrother" both will be different identifier. It can't be same as any other identifier declared in the class.


    Parameter List:

    The Parameter are Enclosed between parentheses "()", the parameter are used to pass and receive data from a method. the Parameter list refers to the type, order, and number of the parameters of a method. parameters are optional, that is, a method may contain no parameters.


     //method with parameter.
     public int Sum(int x, int y)   
       {
          //method body:
       }
    
     //method without Parameter having return type void:
     public void text()
      {
           //method body: 
      }


    Method Body:

    The method body contain the set of instructions needed to complete the required activity.




Example:

Let's have an example where we will learn how to define the method. in this example, we will define two methods in same class. the 1st method Sum will take two integer arguments and return the sum. The second method Text will be void without any arguments to display some text. both methods has Public specifier, so it can be accessed from outside the class using an instance of the class.

 class Program
    {
        //method with parameter.
        public int Sum(int x, int y)   
        {
            int result;
            result = x + y;
            return result;  //return x+y:
        }

        //method without Parameter having return type void:
        public void text()
        {
            Console.WriteLine("Hello every one: ");
        }
 
    }


Calling Methods In C#:

We define the Method above, now its time to call or invoke the method in our Main() Program. When a Program call a method, the control is transferred to the called method. then the method will perform its task and return the control back to main method.

In order to call the method in our main program, we need to create object of containing class, then followed by .(dot) Operator we can call the method. as shown in Example:


/*Example: Methods in C#: InfoBrother:*/

using System;

namespace methods
{
    class Program
    {
        //method with parameter.
        public int Sum(int x, int y)   
        {
            int result;
            result = x + y;
            return result;  //return x+y:
        }

        //method without Parameter having return type void:
        public void text()
        {
            Console.WriteLine("Hello every one: ");
        }

        //main method begin:
        static void Main(string[] args)
        {
            int a = 20;
            int b = 30;
            int ret;

            Program pro = new Program();  //creating object:
            ret = pro.Sum(a, b);  //calling 1st function:
            Console.WriteLine("The sum is : " + ret);

            pro.text();  //calling 2nd function:
            Console.ReadKey();
        }
    }
}


After defining the method, we need to call it in our main() method to perform its operation. as we discuss already, the code define in main() method body will be execute only. the Other method could be define outside the main() method body, but we need to call it in main() Method to perform its operation:



We can also call any Public method from other classes by using the object or instance of the class. we can define the method in one class, and can call in another class using the object of that class where we define the method:



Recursive Method Call:

A method can call itself, known as Recursive Method. A Recursive usually has the two specification:


  • » Recursive Method calls itself so many times until being satisfied.
    » Recursive method has parameter(s) and calls itself with new parameter values.



Let's have an simple example to know how this recursive method work. In this example, we will calculate factorial for a given number using a recursive method:



/*Example: Recursive Methods in C#: InfoBrother:*/

using System;

namespace methods
{
    class Program
    {        
        public static long Factorial(long Number) 
        {
            long ReturnValue;
            long NextNumber;


            NextNumber = Number - 1;
            if (Number == 1)
            {
                //This is the base case that stops the recursion.
                ReturnValue = 1;
            }
            else
            {
                //This is what makes it recursion because it calls itself.
                ReturnValue = Factorial(NextNumber) * Number;
            }


            return ReturnValue;
        }


        static void Main(string[] args)
        {
            bool ExitLoop = false;
            long UsersNumber = 0;


            do
            {
                Console.Write("Enter a number to calculate it's factorial (or 0 to exit): ");
                UsersNumber = Convert.ToInt16(Console.ReadLine());
                if (UsersNumber > 0)
                {
                    if (UsersNumber > 20)
                    {
                        Console.WriteLine("Numbers entered must be between 1 and 20:");
                    }

                    else
                    {
                        //The recursion happens when the Factorial method is called.
                        Console.WriteLine("The Factorial of " + UsersNumber + " is " 
                                                              + Factorial(UsersNumber));
                    }
                }

                else
                {
                    if (UsersNumber == 0) ExitLoop = true;
                    Console.WriteLine("The number must not be negative.");
                    Console.ReadKey();
                }

            }
            while (!ExitLoop);
        }

    }
}


Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the "formal parameters" of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are three ways that arguments can be passed to function.



Call TypeDescription
Value Parameters: In C# all Methods arguments are passed "by value". this means that the called method is given the values of its arguments in temporary variables rather than the originals. in this case, changes made to the parameter inside the method have no effect on the argument. (read more...)
Reference Parameters: This method copies the reference of an argument into the formal parameter. inside the Method, the reference is used to access the actual argument used in the call. this means that changes made to the parameter affect the arguments. (read more...)


Whenever we Writing a program, always keep in mind that it could be reused at some other time. also try to write in a way that it can be used to solve some other related problem. Methods are very important in case of re-usability. We can write some advance method and can use these methods in other programs. method provide us the way through which we can break our code into small pieces and make it more readable and efficient.















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement