Mike
Mike

Reputation: 616

Polymorphism in practice c#

So I currently have an address book program (purposely basic as didn't fancy writing anything more fancy) so a module of an assessment being done (this is not school work).

I have to demonstrate polymorphism, encapsulation and inheritance in this module.

I was wondering if implementing IEnumerable counts as polymorphism as shown below?

public class AddressBookEnumerator : IEnumerator
{
    #region IEnumerable Implementation
    public Person[] Contacts;
    int Position = -1;

    public AddressBookEnumerator(Person[] ContactList)
    {
        Contacts = ContactList;
    }

    public bool MoveNext()
    {
        Position++;
        return (Position < Contacts.Length);
    }

    public void Reset()
    {
        Position = -1;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public Person Current
    {
        get
        {
            try
            {
                return Contacts[Position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
    #endregion
}

I only wonder if it is because of inheriting the IEnumerator class and then creating new methods with different behaviour in for my specific class? Or am I just misunderstanding how IEnumerator works.

Upvotes: 0

Views: 1154

Answers (3)

Jodrell
Jodrell

Reputation: 35716

I'll try to break it down quickly,

interface IOrganism
{
    string GetSpecies();
}

abstract class Animal : IOrganism
{
    abstract string GetSpecies();
}

class Rat : Animal
{
   public virtual string GetSpecies()
   {
      return "Ratus";
   }
}

sealed class BlackRat : Rat
{
    public override string GetSpecies()
    {
       return string.Format("{0} Ratus", base.GetSpecies()));
    }
}

Animal, Rat and BlackRat are all polymorphic with IOrganism. Rat and BlackRat are polymorphic with Animal. Lastly, BlackRat is polymorphic with Rat.


This means, I can write a function,

void OutputSpecies(IOrganism organism)
{
    Console.WriteLine(organism.GetSpecies());
}

It can accept any implementor of IOrganism, whether that be Rat, BlackRat or some future implementor, becuase they are all polymorphic with IOrganism.


So, to answer the original question, implementing an interface, like IEnumerable and using it as an argument to a function is using polymorphism. However, your code just implements IEnumerator, so is kind of half way there. It shows the potential for polymorphism but not polymorphism in practice.

Additionally, using IEnumerator as an example may distract from the desired task and you might be better to keep your example more abstract.

Upvotes: 1

Mike
Mike

Reputation: 6239

Whilst you can consider treating types at interface level as polymorphism, for the more academic approach, they are probably thinking more along these kind of lines?

Here we see:

  • Inheritance from the abstract base class Employee
  • Encapsulation / Polymorphism when we refer to the GetBonusMultiplier method. We are able to refer to the method from the abstract base class and we are also unaware of the internals of how each type determines the base multiplier. All we know / care is that when we call the method, we get an int value back.

If you wanted to change Employee to an interface IEmployee it would be simple. I would probably still have some kind of abstract base to capture the common fields though so you don't have to reimplement in each class that implements IEmployee.

class Program
{
    static void Main(string[] args)
    {
        var employees = new List<Employee>
        {
            new Manager(1, "Dave Smith"),
            new Director(2, "Peter Thompson")
        };

        foreach (Employee employee in employees)
        {
            Console.WriteLine(string.Format("Employee ID: {0}. Employee Name: {1}. Bonus Multiplier: {2}.", employee.Id, employee.Name, employee.GetBonusMultiplier()));
        }
        Console.ReadKey();
    }
}

abstract class Employee
{
    public int Id { get; protected set; }
    public string Name { get; protected set; }

    public abstract int GetBonusMultiplier();
}

class Director : Employee
{
    public Director(int employeeId, string name)
    {
        Id = employeeId;
        Name = name;
    }

    public override int GetBonusMultiplier()
    {
        return 3;
    }
}

class Manager : Employee
{
    public Manager(int employeeId, string name)
    {
        Id = employeeId;
        Name = name;
    }

    public override int GetBonusMultiplier()
    {
        return 2;
    }
}

Upvotes: 1

Tigran
Tigran

Reputation: 62256

Polymorphism is a

a programming language feature that allows values of different data types to be handled using a uniform interface.

In current code provided I see only one datatype you operate on.

Implementing IEnumerable is about subscribing to contract of a given interface, so your type can be threat like that interface. I, personally, would not dimonstrate this code like polymorphism example.

Upvotes: 1

Related Questions