views:

171

answers:

2

Scenario

I have a single base class and 2 (possibly 3) other classes that derive from that base class.

 //Base Class
 class RateInstrument
 {
    public string Ric { get; set; }

    public string Tenor { get; set; }
    public double Rate { get; set; }

    public DateTime Date { get; set; }
    public double Price { get; set; }

    public double Bid { get; set; }
    public double Ask { get; set; }

    public RateInstrument(string tenor, double rate)
    {
        Tenor = tenor;
        Rate = rate;
    }

    public RateInstrument(DateTime date, double price)
    {
        Date= date;
        Price = price;
    }
   }

    //Derived Class 1
    class Swap : RateInstrument
    {
    public Swap(string tenor, double rate): base(tenor,rate)
    {
    }

    }

     //Derived Class 2
     class Future: RateInstrument
     {
    public Future(DateTime date, double price): base(date,price)
    {

    }
    }

Question

On occasions I may need to have a collection of ALL Rate Instruments, and sometimes just a collection of each individual RateInstrument itself. Realistically what I wanted was to employ some methods in the Base class to do this however I'm not entirely sure how to go about it. It is important to me to structure the code well to help my learning etc. Any help would be greatly appreciated.

EDIT----------

Sorry I meant to say in the essence of being able to instantiate a collection of objects in shorthand. Particularly if I have to create say 100 at a time.

+2  A: 

In C# 3.5 you don't really need to do anything in particular for that. IEnumerable<RateInstrument> will do fine.

If you want only particular subtypes, you can use the OfType extension method:

var swaps = instruments.OfType<Swap>();
Mark Seemann
+1  A: 

Doesn't your existing code do the trick?

List<RateInstrument> instruments = new List<RateInstrument>();
instruments.Add(new Swap("bla", 100));
instruments.Add(new OtherSwap("bla2", 200));

var swapInstruments = from instrument in instruments where instrument Is Swap select instrument;
Jan Jongboom