Search code examples
c#inheritancemethodshidesortedlist

Hide SortedList's .Add method vs using another method name with base.Add


I have a custom class that is basically a SortedList with a few extra properties and methods. I would like to do some additional processing when a new key/value pair is added (i.e when the .Add method is called). I can hide the .Add method or use another method name (ex:.AddPair) and then call base.Add in that method. Preferred approach? Why?

Hide .Add method:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;    
namespace Inheritence_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            DYseries d = new DYseries() { FieldName = "test" };
            d.Add(new DateTime(2010, 12, 1), 2345);
            d.Add(new DateTime(2010, 12, 5), 2340);
            d.Add(new DateTime(2010, 12, 2), 2343);
            Console.WriteLine("fieldName {0} \n count {1} \n max {2} \n min {3}", d.FieldName, d.Count(), d.Keys.Max(), d.Keys.Min());
        }
    }
    class DYseries : SortedList<DateTime, double>
    {
        public string FieldName { get; set; }
        new public void Add(DateTime date, double value)
        {
            base.Add(date,value);
            // additional processing here
            Console.WriteLine("Added date {0}.\n   Max date: {1}",date, this.Keys.Max());
        }

    }
}

or

using another method name:

class Program
    {
        static void Main(string[] args)
        {
            DYseries d = new DYseries() { FieldName = "test" };
            d.AddPair(new DateTime(2010, 12, 1), 2345);
            d.AddPair(new DateTime(2010, 12, 5), 2340);
            d.AddPair(new DateTime(2010, 12, 2), 2343);
            d.AddPair(new DateTime(2010, 12, 9), 2348);
            Console.WriteLine("fieldName {0} \n count {1} \n max {2} \n min {3}", d.FieldName, d.Count(), d.Keys.Max(), d.Keys.Min());
        }
    }
    class DYseries : SortedList<DateTime, double>
    {
        public string FieldName { get; set; }
        public void AddPair(DateTime date, double value)
        {
            base.Add(date,value);
            // additional processing here
            Console.WriteLine("Added date {0}.\n   Max date: {1}",date, this.Keys.Max());
        }

    }

Is there a preferred approach? Will one approach (hiding?) potentially cause problems?


Solution

  • Use the second approach. The first breaks good OO design, and you're not going to be sure if your method will be called or the base class. Consider this use of your class:

    SortedList<DateTime, double> myList = new DYseries();
    myList.Add(date, value);  // This will call the base, not your implementation!
    

    I've never come across a valid reason to use new; there are always other ways to acomplish what you want without breaking good OO design.