Polymorphism in C#

with the help of this small code, I’ll try to explain you the polymorphism.

using System;
using System.Collections.Generic;
using System.Text;

namespace CSharpBasics
{
    class Polymorphism_bas
    {
        public string s_method()
        {
            return "base";
        }

        //Not mandatory to override a virtual method
        public virtual string s_method1()
        {
            return "base1";
        }
    }

    class Polymorphism_der : Polymorphism_bas
    {
        //Eiether you can use new keyword or not..really doesn't
        //matter just to used to shadow the base class
        //functionality which nay ways is done.
        public string s_method()
        {
            return "der";
        }

        public string over_1(int i)
        {
            return "s";
        }

        public new string s_method1()
        {
            return "der1";
        }

        public void s_param(int i, params int[] arr)
        {
            Console.WriteLine("params = " + i.ToString() + " - " + arr.Length.ToString());
        }

        //ERROR - params has to be the last paramter in the list

        //public void s_param(int i, params int[] arr, int j)
        //{
        //    Console.WriteLine("params = " + i.ToString() + " - " + arr.Length.ToString());
        //}

        public void s_param(int i, int j)
        {
            Console.WriteLine("with out params = " + i.ToString() + " - " + j.ToString());
        }

        //ERROR - Cannot have same method name with same
        //parameter list and diff return type.

        //public int over_1(int i)
        //{
        //    return 1;
        //}

    }

    class program
    {
        static void Main(string[] args)
        {
            Polymorphism_der p_der = new Polymorphism_der();
            p_der.s_param(1, 5); //Will call int,int method as there is an exact prototype available for this.
            p_der.s_param(1, 1, 2); //Will call int,params method as there is an exact prototype available for this.

            int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            p_der.s_param(1, arr); //We can also pass array.
            p_der.s_param(1, new int[] { 1, 2, 3, 4, 7, 8 });

        }
    }
}

Output

***********Polymorphism****************
with out params = 1 - 5
params = 1 - 2
params = 1 - 8
params = 1 - 6
Tags: , ,

Leave a Reply

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

*
*