Inheritance Example

Expanding on the simple Gradebook program. This implements a ThrowAwayGrade class that inherits from the GradeBook class. Inheritance being one of the pillars of OOP programming. I’ll be going over basic inheritance, polymorphism, and interfaces in the next few blog posts. So keep an eye out.

If you want to see the entire source code you can get that HERE. Or by going to the downloads page.

InheritanceProgram

 

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 GradeStatistics ComputeStatictics()
        {
            float lowestGrade = float.MaxValue;
            foreach (float grade in _grades)
            {
                lowestGrade = Math.Min(lowestGrade, grade);
            }
            _grades.Remove(lowestGrade);
            return base.ComputeStatictics();
        }
    }
}

This class inherits from the GradeBook base class. The main purpose of this class is to review all of the grades in the gradebook list and remove the lowest score. The ComputeStatistics method does this then returns to the ComputeStatistics method on the base Gradebook class to perform the rest of the operations.

 
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);
        }

        public GradeStatistics ComputeStatictics()
        {
            // 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("*************************");
             */

        }
    }
}

Once the ComputeStatistics method in the ThrowAwayGrade class has finished executing the program return back to the ComputeStatistics in the GradeBook class. From here this class finishes figuring out the highest, lowest, and average grades. Minus the lowest score of course.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s