How to pass an abstract class as an instance type parameter?

So, I have a type called FunBond , with a default constructor like this

 public FunBond(int id, string name, Currency currency, double notional, DateTime maturityDate, List<CashFlowWithDate> couponCashFlows, DayCounter dayCounter) : base(id, name, notional, InstrumentType.FixedRateBond, currency, maturityDate, dayCounter) { ... } 

And DayCounter is an abstract class

 public abstract class DayCounter { public abstract string Name(); public abstract double YearFraction(DateTime d1, DateTime d2); public abstract int DayCount(DateTime d1, DateTime d2); } 

Now my question is: what should I imagine as a DayCounter to create an instance of FunBond ? I can specify id, name, currency, ... etc. Etc. For passing FunBond as parameters, but what should a DayCounter be? I cannot create an instance of this object, and I cannot provide it with anything that I do not think ... I thought that I would need another class derived from my abstract class to provide FunBond , so I think I misunderstand something fundamentally.

+5
source share
2 answers

The constructor declares that it requires a parameter of type DayCounter . Since DayCounter is an abstract class, you need to pass an instance of the class that comes from DayCounter .

This does not mean that you need to change the type of the constructor parameter, just pass an instance of the derived type.

The reason someone defines an abstract type parameter is to allow polymorphism and loose coupling. You may have different derived DayCounter classes, each of which behaves differently (subject to a DayCounter contract). And FunBond can talk with examples of such classes without knowing how they work domestically. As for FunBond , it talks to an object that adheres to the DayCounter contract, but no matter how it is implemented internally.

+6
source

The question says:

I thought that I would need another class derived from my abstract class to provide FunBond

That's right - you need to create a specific class from the abstract.

 // Your derived class public class WeekdayCounter : DayCounter { public override string Name() { return "Weekday" } public override double YearFraction(DateTime d1, DateTime d2) { return 0.0; } public override int DayCount(DateTime d1, DateTime d2) { return 0; } } // Create a FunBond WeekdayCounter c = new WeekdayCounter(); // **derived class** FunBond yay = new FunBond(id, name, currency, notional, maturityDate, couponCashFlows, c); // **WeekdayCounter, which is a DayCounter** 
0
source

Source: https://habr.com/ru/post/1240529/


All Articles