[Solved] please clear – To achieve runtime polymorphism in c# we use Interface? [closed]


You don’t have to define seperate interfaces for this. You can also use a baseclass to achieve polymorphism.

For more info check this page:

Polymorphism – C# programming

Example of using polymorphism in C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Animals
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Animal> animals = new List<Animal>();
            animals.Add(new Dog());
            animals.Add(new Cat());

            foreach(Animal animal in animals)
            {
                animal.PrintWhoAreYou();
            }

            Console.ReadKey();
        }
    }

    abstract class Animal
    {
        public abstract void PrintWhoAreYou();

        private bool feeded = false;

        public void Feed()
        {
           feeded = true;
        }
    }

    class Dog : Animal
    {
        public override void PrintWhoAreYou()
        {
            Console.WriteLine("I am a dog!");
        }
    }
    class Cat : Animal
    {
        public override void PrintWhoAreYou()
        {
            Console.WriteLine("I am a cat!");
        }
    }
}

As you can see using a base class you can define common functionality in the base class, instead of repeating code.

You can use an interface to define a set of public methods that are offered by the classes those are realizing this interface.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Animals
{
    class Program
    {
        static void Main(string[] args)
        {
            List<IAnimal> animals = new List<IAnimal>();
            animals.Add(new Dog());
            animals.Add(new Cat());

            foreach(Animal animal in animals)
            {
                animal.PrintWhoAreYou();
            }

            Console.ReadKey();
        }
    }

    interface IAnimal
    {
        void PrintWhoAreYou();
    }

    abstract class Animal : IAnimal
    {
        public abstract void PrintWhoAreYou();

        private bool feeded = false;

        public void Feed()
        {
            feeded = true;
        }

    }

    class Dog : Animal
    {
        public override void PrintWhoAreYou()
        {
            Console.WriteLine("I am a dog!");
        }
    }
    class Cat : Animal
    {
        public override void PrintWhoAreYou()
        {
            Console.WriteLine("I am a cat!");
        }
    }
}

solved please clear – To achieve runtime polymorphism in c# we use Interface? [closed]