user3378165
user3378165

Reputation: 6916

Object consisting of two objects

I have a class Loan:

public class Loan
{
    public int ID { get; set; }
    public int ClientID { get; set; }
    public string PropertyAddress { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    //etc..
}

And a class Client:

public class Client
{
    public int ID { get; set; }
    public string Company { get; set; }
    public string FirstName { get; set; }
    public string Address { get; set; }
    // etc..
}

I need a ClientWithLoan object, as there is no multiple inheritance in C# what would be the correct pattern for that?

Upvotes: 1

Views: 435

Answers (2)

John Wu
John Wu

Reputation: 52290

Two options:

Distinct class

If a ClientWithLoan is to be a distinct type from a Client then you could do it this way:

class ClientWithLoan : Client
{
    public Loan Loan { get; set; }
}

You might also want to include some validation:

class ClientWithLoan : Client
{
    protected Loan _loan;

    public Loan Loan 
    { 
        get { return _loan; }
        set
        {
            if (value.ClientID != this.ID) throw ArgumentException();
            _loan = value;
        }
    }
}

Keep what you have

Just add a Loan property to your Client class, and leave it null if that particular client has no loan.

public class Client
{
    public int ID { get; set; }
    public string Company { get; set; }
    public string FirstName { get; set; }
    public string Address { get; set; }
    public Loan Loan { get; set; }
}

Upvotes: 4

Yennefer
Yennefer

Reputation: 6234

When you require multiple inheritance in a language with single inheritance, using interfaces usually solves the issue.

You could do this in this way:

public interface ILoan
{
    public int ID { get; set; }
    public int ClientID { get; set; }
    public string PropertyAddress { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    //etc..
}

public interface IClient
{
    public int ID { get; set; }
    public string Company { get; set; }
    public string FirstName { get; set; }
    public string Address { get; set; }
    // etc..
}

public interface IClientWithLoan: IClient, ILoan
{
}

public sealed class ClientWithLoan: IClientWithLoan
{
    // here place the real implementation
}

This approach gives you the flexibility you ask.

Upvotes: 3

Related Questions