-3

For example:

public class AssetCollection : List<Asset>

How can that be used as opposed to a normal inheritance from a class? I can't use something like that normally as I can with storing strings in List<string> or int, etc, so how can this be used?

Jezza
  • 7
  • 6

1 Answers1

0

Here you created a new class type that extends the functionnalities of a List<Asset> to specialize its behaviors.

For example you can add a property to indicate the total amount:

using System.Linq;

public class AssetCollection : List<Asset>
{
  public int Total
  {
    get
    {
      return Items.Sum(asset => aasset.Amount);
    }
  }
}

Here we use the Linq extension method to do the sum of each asset amount that is in the list.

Thus you can add any fields, any properties and any methods you want or need to manage a list of assets.

But here all the public properties and methods of the list are exposed.

Generally we want to have a strong encapsulation and only offer what is needed and we write:

public class AssetCollection
{
  private readonly List<Asset> Items = new List<Asset>();

  public int Count
  {
    get { return Items.Count; }
  }

  public int Total
  {
    get
    {
      return Items.Sum(asset => aasset.Amount);
    }
  }

  public void Add(Asset asset)
  {
    Items.Add(asset);
  }
}

Therefore we wrap all needed behaviors to the list items and forget what we want to protect but use to manage the list internally.

This is called composition instead of using inheritence.

https://www.tutorialspoint.com/composition-vs-aggregation-in-chash

https://www.c-sharpcorner.com/article/difference-between-composition-and-aggregation/