I have two model interface ILoanModel
and IAmortizationModel
.
public interface ILoanModel
{
string ID { get; set; }
IEmployeeModel Borrower { get; set; }
// ******* other propeties *********
ICollection<Model.IAmortizationModel> AmortizationTable { get; set; }
}
public interface IAmortizationModel
{
string ID { get; set; }
ILoanModel Loan { get; set; }
// ******* other propeties *********
}
I create another interface that will handle the computation and other function
public interface IAmortization
{
// Compute and generate amortization table
Model.ILoanModel Generate(Model.ILoanModel loan);
// **** Other function *****
}
Currently I have 3 type of loans and all them have same way of computation and generation of amortization table.
public abstract class Amortization : Controller.Computation.Interface.IAmortization
{
public virtual Model.ILoanModel Generate(Model.ILoanModel loan)
{
// **** other code *******
//Create the amortization table
decimal last_Amortization_RunningBalance = loan.Amount;
loan.AmortizationTable = new List<Model.IAmortizationModel>();
for (int x = 1; loan.NumberOfPayment >= x; x++)
{
// having problem here because Model.IAmortizationModel is a interface
var newAmortizationRow = new Model.IAmortizationModel
{
ID = Guid.NewGuid().ToString(),
AmortizationAmount = loan.AmortizationPaymentAmount,
AmortizationInterest = loan.AmortizationPaymentAmount* loan.Nominal,
AmortizationPrepayment =
loan.AmortizationPaymentAmount
- (loan.AmortizationPaymentAmount * loan.Nominal),
AmortizationOutstandingBalance =
last_Amortization_RunningBalance
- (loan.AmortizationPaymentAmount
- (loan.AmortizationPaymentAmount * loan.Nominal)),
Sequence = x
};
last_Amortization_RunningBalance -=
newAmortizationRow.AmortizationOutstandingBalance;
loan.AmortizationTable.Add(newAmortizationRow);
}
}
}
My problem now is generating new IAmortizationModel
that will be added to the loan.AmortizationTable
. How can I get the type of loan.AmortizationTable
and create?
One option would be to make it generic and add a generic constraint with new()
:
public virtual Model.ILoanModel Generate<T>(Model.ILoanModel loan)
where T:IAmortizationModel, new()
and then call new T()
An alternative option would be to pass a generator function:
public virtual Model.ILoanModel Generate(Model.ILoanModel loan,
Func<IAmortizationModel> generator)
and call generator()