MSMVPS.COM
The Ultimate Destination for Blogs by Current and Former Microsoft Most Valuable Professionals.

Collections, derived types and generics

I'm sure someone has come up with this solution to collections of derived types in derived objects somewhere before, but I couldn't find the solution written up anywhere when I was trying to solve it, so I though I'd write it up for the sake of easy reference.

Suppose you have the following types to represent line items on an EDI document (property accessors removed to reduce code clutter):

class LineItem
{
string GoodDescription;
string ID;
}


class PurchaseOrderLineItem : LineItem
{
public decimal UnitPrice;
}

class ForecastLineItem : LineItem
{
public int DaysAhead;
}

There are a number of different types of EDI documents, all of which contain line items and all derived from a base EDI document, but how do you express the relationship between the elements in the collection without repeating the declaration of the collection in each derived EDI document type (which would kill the ability to handle the line items polymorphically) and yet still maintain strong typing so a forecast document could only store forecast line items?

The solution I cam up with was to use generics and generic constraints:

class EDIDocument<T> where T : LineItem
{
public List<T> LineItems;
}

class Forecast : EDIDocument<ForecastLineItem >
{
}

class PurchaseOrder : EDIDocument<PurchaseOrderLineItem>
{
}

With this solution, you get the two big wins and polymorphism and strong-typing at compile time, and this is achieved without a lot of extra code or any run-time performance penalty. After working on a project that (for a variety of reasonable technical and business issues) was stuck on .NET 1.1, solving real problems with generics is enjoyable.
Posted Apr 04 2007, 01:13 AM by nick
Filed under:


Copyright © is the original authors. Blog site is an independent site not sponsored by Microsoft. The Yoda blog server and the Brianna SQL server would like to thank www.ownwebnow.com and www.exchangedefender.com. They wouldn't be here and broadcasting without the generosity of Vlad Mazek and his companies.

Powered by Community Server (Commercial Edition), by Telligent Systems