Despite there are some information in answers to these questions: Cast IList to List and Performance impact when calling ToList() they do not answer my specific question. I have a class that is a wrapper around List. This class was designed to be sent via WCF services and implements some additional functionality.
[DataContract]
public class DataContractList<T> : IList<T>
{
[DataMember]
protected readonly List<T> InnerList;
public DataContractList()
{
InnerList = new List<T>();
}
public DataContractList(IList<T> items)
{
InnerList = items as List<T> ?? items.ToList(); //Question is about this line.
}
}
So there is a constructor that accepts an IList<T>
interface (in order to encourage programming to interface). I need to convert this IList<T>
interface to List<T>
class. I can use .ToList()
extension method which internally creates a new instance of List<T>
by passing IEnumrable "this" argument to it's constructor (see here). Generic List<T>
constructor just iterates through this enumberable. So I would like to prevent this iteration if it's not necessary (in case inner items parameter is already a List<T>
). So, is it an optimal way (in terms of performance and readability) to do this: InnerList = items as List<T> ?? items.ToList();
? If no, please provide with details about better way and why.