Constantine Constantine - 2 months ago 20
C# Question

Declaring class as properties inside another class

I copied this code from this article and I don't get any idea why define class inside classes as properties. Also, what happens when the class

PersonalLoan
is instantiated ?

public class PersonalLoan
{
public string AccountNumber { get; set; }
public string AccounHolderName { get; set; }
public Loan LoanDetail { get; set; }
public PersonalLoan(string accountNumber)
{
this.AccountNumber = accountNumber;
this.AccounHolderName = "Sourav";
this.LoanDetail = new Loan(this.AccountNumber);
}
}
public class Loan
{
public string AccountNumber { get; set; }
public float LoanAmount { get; set; }
public bool IsLoanApproved { get; set; }
public Loan(string accountNumber)
{
Console.WriteLine("Loan loading started");
this.AccountNumber = accountNumber;
this.LoanAmount = 1000;
this.IsLoanApproved = true;
Console.WriteLine("Loan loading started");
}
}

Answer

I suspect that this code snippet is an example of what you should avoid: LoanDetail property of type Loan inside a class PersonalLoan suggests a has-a relationship between the classes. In other words, the authors of this code snippet are trying to say that

Personal loan has a Loan

This, however, is unlikely the relationship that they are trying to model: in reality,

Personal loan is a Loan

The relationship is-a is modeled using inheritance, not composition. In other words, they should have written this:

public class PersonalLoan : Loan {
    public PersonalLoan(string accountNumber) : base(accountNumber) {
        ...
    }
    ...
}

Another issue that points to the model being incorrect is that both PersonalLoan and the Loan inside it have the same accountNumber, which is stored in two places within the same object. When you see this, you know something is not right. The reason you get two account numbers is that when PersonalLoan gets instantiated, its constructor also instantiates Loan, passing it the same accountNumber.

This is not to say that embedding objects inside other objects is wrong. For example, if you were to model a borrower address as a class, you would end up with something like this:

class Address {
    public string Country {get;set;}
    public string City {get;set;}
    ... // And so on
}
class Borrower {
    public Address MailingAddress  {get;set;}
    ... //
}

This model is perfectly valid, because Borrower has an Address.

Comments