Wednesday, June 5, 2013

Compile time Polymorphism

In C# Static Polymorphism or Compile time Polymorphism is achieved through function/method overloading.

Function overloading refers to having many functions with the same name but with different signatures i.e the names of the functions will be same but will vary in any one of the following.

1. Number of parameters
2. Type of parameters
3. Return Type.

The following example explains Static or compile time Polymorphism.
    class StaticPolymorphism
    {
        public int add(int nNumber1, int nNumber2)
        {
            return nNumber1 + nNumber2;
        }
        //
        public double add(double nNumber1, double nNumber2)
        {
            return nNumber1 + nNumber2;
        }
    }

The above class contains two methods with the same name add(), but they vary in the type of input parameters it takes. We can create an instance of the class and call both the methods by passing the overloaded type of parameters as follows.

    StaticPolymorphism objStaticPolymorphism = new StaticPolymorphism();
    Console.WriteLine("Add Integers:" + objStaticPolymorphism.add(1, 2).ToString());
    Console.WriteLine("Add Decimals:" + objStaticPolymorphism.add(1.5, 2.5).ToString());


Here the first add method will call the add function which takes int parameters and the second add method call will calls the function which takes double parameters. The runtime decides which method to be called based on the types of the parameters and return values.

Search Flipkart Products:
Flipkart.com

No comments: