I understand that this question has already been answered, but I missed a simple explanation of the problem behind your question, so it says here:
The reason you cannot assign the SampleDataSource class to the IEnumerable<object> field is because SampleDataSource does not implement IEnumerable<object> . Although it implements IEnumerable , it is not very good because IEnumerable<object> is a subtype of IEnumerable .
Due to covariance of the interface, you can assign a class to the IEnumerable<object> field if it implements IEnumerable<MyObject> , provided that MyObject is actually a reference type (i.e. a class). However, this only applies to C # 4.0 and later.
Reed Copsey's answer does not mention that you can declare a SampleDataSource class this way because IEnumerable<T> inherits from IEnumerable :
public class SampleDataSource : IEnumerable<MyObject>
Also, since you just wrap the contained collection, you usually implement it this way:
public class SampleDataSource : IEnumerable<MyObject> { public List<MyObject> Subjects { get; private set; } public IEnumerator<MyObject> GetEnumerator() { return Subjects.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
This is doubtful from the point of view of object orientation, because, since you provide public access for reading and writing to the list. (The fact that the setter is closed means that the public cannot reassign the link to the list, but this does not stop them from calling Add or Remove or Clear in the list.)
Another object orientation question is to ask: if the SampleDataSource contains the sequence MyObjects, why will it also be the sequence MyObjects? Instead of this:
classICannotAlter.Items = (IEnumerable<object>)someSampleDataSourceInstance;
maybe you should do this:
classICannotAlter.Items = (IEnumerable<object>)someSampleDataSourceInstance.Subjects;