Tech Off Post

Single Post Permalink

View Thread: Generic Base class problem
  • User profile image

    I'm wondering if anyone has some insight to this problem.

    I'm working with a business object base class that uses generics to return strongly typed data for some of the static methods.

    public class BusinessObjectBase<T>
          public static IList<T> GetAList()
                IList<T> listOfBusinessObjects = new List<T>();
                // code to populate the list.
                return listOfBusinessObjects

    The business object base class of course does a lot more but this is a good example why I decided to use generics.

    I have a deriving class Customer:

    public class Customer : BusinessObjectBase<Customer>

    First this seems overly redundant specifying the type for the business base right after the declaration of the Customer type, but it sure beats passing the Customer type to every generic static method. Probably look something like this.

    IList<Customer> customers = Customer.GetAList<Customer>();

    So adding the generic to the base class made sense. This looks a lot cleaner:

    IList<Customer> customers = Customer.GetAList();

    I ran into this problem however. I wanted to add a bunch of specific things to the Customer class, but since I have other applications that use the Customer class, I decided to derive from it.

    public class SpecialCustomer: Customer

    This worked great until I wanted to call the static methods on the base class.

    IList<SpecialCustomer> specialCustomers = SpecialCustomer.GetAList();

    The compiler notified me that SpecialCustomer.GetAList() actually returned IList<Customer>. WHAT! Yep, SpecialCustomer implements Customer which implements BusinessObjectBase<Customer>. This was apparently obvious to everyone but me.

    So Is there anyway to resolve this. I certainly cant add a generic to Customer.

    public class Customer<T> : BusinessObjectBase <T>

    It'd work for SpecialCustomer:

    public class SpecialCustomer: Customer<SpecialCustomer> {}

    But just cause you can do it, doesn't mean it's to be done. That would look sweet defining a regular customer.

    Customer customer = new Customer<Customer<Customer< Customer<Customer<Customer<Customer<Customer< Customer<Customer<Customer... Ugh...

    Being a noob sux Perplexed