Polymorphism Example

Here’s another example of the Gradebook program that I’ll demonstrate some simple polymorphism. Polymorphism being another pillar of object oriented programming.

You can find this programs source code HERE. Or by visiting the downloads page.

PolymorphismProgram

 

ThrowAwayGrade.cs code contents

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

namespace _1.Grades
{
    public class ThrowAwayGrade : GradeBook
    {
        // Constructors
        //
        public ThrowAwayGrade() : base()
        {
            Console.WriteLine("Running From The ThrowAwayGrade Class Without A Parameter");
        }

        public ThrowAwayGrade(string name) : base(name)
        {
            Console.WriteLine("Running From The ThrowAway Class With A Parameter");
        }

        // Public Methods
        //
        
        // Method that takes care of removing the lowest grade.
        public override GradeStatistics ComputeStatictics()
        {
            Console.WriteLine("Compute Statistics Running From The ThrowAwayGrade Class.");

            float lowestGrade = float.MaxValue;
            foreach (float grade in _grades)
            {
                lowestGrade = Math.Min(lowestGrade, grade);
            }
            _grades.Remove(lowestGrade);
            return base.ComputeStatictics();
        }
    }
}

The first thing you notice is that I’m overriding the ComputeStatistics method. The method still performs the same, removing the lowest grade. I’m using the virtual and override keywords on the methods. That way when this object is created the overriding ComputeStatistics method will run.

 
GradeBook.cs code contents

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

namespace _1.Grades
{
    public class GradeBook
    {
        // Private Fields.
        //
        protected List<float> _grades;
        private string _name;

        // Public fields.
        //
        public event NameChangedDelegate NameChanged;     // This is just a public field created for the event delegate.

        // Public backing method that gets or sets the name.
        public string Name
        {
            get
            {
                // If the name of the book is invalid
                if (String.IsNullOrEmpty(_name))
                    return "No Book Name Was Given";
                else
                    return _name;
            }
            set
            {
                // Checking to make sure you can change the name to null or empty.
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException("The name cannot be null or empty.");
                }

                if (_name != value)
                {
                    // Need to do something that announces that the name has changed.
                    var oldNameValue = _name;   // This is to capture the old value before it changes.
                    _name = value;
                     
                    // Do some checking to keep an exception from happening.
                    if (NameChanged != null)
                    {
                        // Creating the event args delegate object.
                        NameChangedEventArgs args = new NameChangedEventArgs();
                        args.OldValue = oldNameValue;
                        args.NewValue = value;
                        NameChanged(this, args);    // Passing this and the args object as parameters.
                    }
                }
            }
        }

        // Constructors.
        //
        public GradeBook()
        {
            Console.WriteLine("Running From The GradeBook Class Without A Parameter");
            _grades = new List<float>();
        }

        public GradeBook(string name)
        {
            Console.WriteLine("Running From The GradeBook Class With A Parameter");
            _name = name;
            _grades = new List<float>();
        }

        // Public methods
        //
        public void AddGrade(float grade)
        {
            // Adding some validation logic before adding the grade to the collection.
            if (grade >= 0 && grade <= 100)
                _grades.Add(grade);
        }

        // Over rid able method that computes the grade stats.
        public virtual GradeStatistics ComputeStatictics()
        {
            Console.WriteLine("Compute Statistics Running From The GradeBook Class.");

            // Creating an instance variable of the class to return.
            GradeStatistics stats = new GradeStatistics();

            // Now to find the average, highest, and lowest grade in the list.
            float sum = 0f;
            foreach (float grade in _grades)
            {
                // Calculating the highest and lowest grade using built-in .NET methods.
                // Comparing the current grade in the loop to the highest grade. If greater then assign the new value.
                stats.HighestGrade = Math.Max(grade, stats.HighestGrade);

                // Comparing the current grade in the loop to the lowest grade. If lower then assign the new value.
                stats.LowestGrade = Math.Min(grade, stats.LowestGrade);
                
                // Adding numbers to the sum variable.
                sum += grade;
            }

            // Calculating the average grade.
            stats.AverageGrade = sum / _grades.Count();     // Normally this would be encased in a try/catch. Possible divide by zero exception.
            return stats;
        }

        public void WriteGrades(TextWriter textWriter)
        {
            // Demonstrating the different ways to iterate using the _grades List.
            // Uncomment the different loops to see what happens.

            // Using a foreach loop.
            textWriter.WriteLine("Grades:");
            foreach (float grade in _grades)
            {
                textWriter.WriteLine(grade);
            }
            textWriter.WriteLine("*************************");

            // Using a for loop.
            /*
            textWriter.WriteLine("Grades:");
            for (int i = 0; i < _grades.Count; i++)
            {
                textWriter.WriteLine(_grades[i]);
            }
            textWriter.WriteLine("*************************");
             */

            // Using a for loop to display the list in reverse.
            /*
            textWriter.WriteLine("Grades:");
            for (int i = _grades.Count - 1; i >= 0; i--)
            {
                textWriter.WriteLine(_grades[i]);
            }
            textWriter.WriteLine("*************************");
             */

            // Using a while loop.
            /*
            textWriter.WriteLine("Grades:");
            int i = 0;
            while (i < _grades.Count)
            {
                textWriter.WriteLine(_grades[i]);
                i++;
            }
            textWriter.WriteLine("*************************");
             */

            // Using a Do/While loop.
            /*
            textWriter.WriteLine("Grades:");
            int i = 0;
            do
            {
                textWriter.WriteLine(_grades[i]);
                i++;
            } while (i < _grades.Count);
            textWriter.WriteLine("*************************");
             */

        }
    }
}

If you look at the ComputeStatistics method in this class you will see that it’s a virtual method now. This is done so I can override this method in the ThrowAwayGrade class. This is a simple example of how you can use inheritance with polymorphism to have the same method perform a different task. In this example I’m running the overriding method to remove the lowest grade then returning to the base method to finish computing the rest of the statistics. The highest, lowest, and average grades.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s