Wednesday, 29 January 2014

Method in C#

                                                                                                                                            Previous....
                                                                                                                                                       Next....

Method are also called as functions.Method are extremely useful because we write logic once and it is used at many places. A method is a group of statement that together perform a task.Every C# program has at lest one class with a method named main.

Syntax of Method

[Attributes]                                                             <Access Specifier> <Return Type> <Method Name>(Parameter)
{
   Method Body
}
  1. Access SpecifierAccess Specifiers defines the scope of a class member. A class member can be variable or function. In C# there are five types of access specifiers are available. We will talk about Access specifier in letter video session.
  2. Return type: A method may return a value. 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.
  3. Method name: Method name is a unique identifier and it is case sensitive. 
  4. Parameter: Enclosed between parentheses, the parameters are used to pass and receive data from a method. .
  5. Method body: This contains the set of instructions needed to complete the required activity.

Example 

public class SimpleMath {
    public static int Add(int x, int y) {
      return x + y;
    } public static int Multiply(int x, int y) {
      return x * y;
    }
}
Here is the test program:
// TestSimpleMath.cs
using System;
public class TestSimpleMath {
    public static void Main(string[] args) {
      int sum = SimpleMath.Add(5, 7); int product = SimpleMath.Multiply(5, 7); Console.WriteLine("sum = {0}", sum); Console.WriteLine("product = {0}", product);
    }
}
O/p
sum = 12
product = 35

                                                                                                                                            Previous....
                                                                                                                                                                                                                                                                                                                     Next....

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...