INotifyCollectionChanged: one step forward

How many times have you seen something like this?

public class Album : Entity, IAlbum
{
    public virtual Artist Artist { get;  set; }
    public virtual string Title { get; set; }

    public virtual IEnumerable<Track> Tracks { get; private set; }
    public virtual void AddTrack(Track track)
    {
        track.Album = this;
        Tracks.Add(track);
    }
    public virtual void AddTracks(IEnumerable<Track> tracks)
    {
        tracks.ForEach(AddTrack);
        
    }
    public Album()
    {
        Tracks = new List<Track>();
    }
}

The question is why is better than this:

public class Album : Entity, IAlbum
{
    public virtual Artist Artist { get;  set; }
    public virtual string Title { get; set; }

    public virtual ICollection<Track> Tracks { get; private set; }

    public Album()
    {
        Tracks = new EditableCollection<Track>();
        Tracks.CollectionChanged += (sender, args) =>
              {
                  if (args.Action == NotifyCollectionChangedAction.Add)
                      args.NewItems.ForEach(track => track.Album = this);
              };
    }
}

Then you can call album.Tracks.Add( .. ) normally. EditableCollection is from my previous post. You can do the same for the remove method.


blog comments powered by Disqus
  • Categories

  • Archives