none
Why is ObservableCollection<T> Constructor (List<T>) and not (IList<T>)? RRS feed

  • Question

  • ObservableCollection<T> inherits from Collection<T> which has the constructor defined as (IList<T>).
    Why not define the parameter as IList<T> or ICollection<T>?

    I can only see that the Count property and the IEnumerable<T> interface is used.

    public ObservableCollection(List<T> list)
        : base((list != null) ? new List<T>(list.Count) : list)
    {
        CopyFrom(list);
    }
    
    private void CopyFrom(IEnumerable<T> collection)
    {
        IList<T> items = Items;
        if (collection != null && items != null)
        {
            foreach (var item in collection)
            {
                items.Add(enumerator.Current);
            }
        }
    }
    The if statement ensures that either a new List<T> or null is passed down to the base class Collection<T>.

    In the case of null an ArgumentNullException exception is  thrown::

    public Collection(IList<T> list) 
    {
        if (list == null) 
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
        }
    
        items = list;
    }




    Thursday, August 13, 2015 1:15 PM

Answers

  • Hi Andreas.Synnerdahl,

    >>Why not define the parameter as IList<T> or ICollection<T>?

     [TypeDependency("System.SZArrayHelper")]
        public interface IEnumerable<out T> : IEnumerable
        {
          System.Collections.Generic.IEnumerator<T>。
            IEnumerator<T> GetEnumerator();
        }
      [TypeDependency("System.SZArrayHelper")]
       public interface ICollection<T> : IEnumerable<T>, IEnumerable
    public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
    public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
    Comparing these interface and Class List<T>, you'll see the differences obviously.

    IEnumerable <T> implements IEnumerable interface, that is IEnumberable what it does, in fact, it is improve the collection can iterate. In a short summary,it is just a iteration.

    List<T> is the only class, not only to achieve their interfaces, but also extends too many ways to be used by us. It almost all functions can be achieved.

    To sum up, this design decided to accept IEnumerable<T> and List<T> will be covered more comprehensive.

    Sort by function: List <T>  IList <T> ICollection <T>  IEnumerable <T>

    Sort by performance : IEnumerable <T> ICollection <T> IList <T> List <T>

    Best regards,

    Kristin


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.




    Friday, August 14, 2015 7:13 AM