Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding IEnumerable<T> to class derived from CollectionBase

Suppose I have a class TestCollection which is used to hold objects of type Test and is defined as

public class TestCollection : CollectionBase

This allows me to iterate through the collection either as

foreach(object o in collection)
...

or

foreach(Test t in collection)

but does not allow me to use new Linq queries.

If I change the definition of the class to

public class TestCollection : CollectionBase, IEnumerable<Test>

and add a method

public new IEnumerator<Test> GetEnumerator()
{
    foreach (Test o in this.List)
        yield return o ;
}

then linq queries are available.

However this new method is not just called for linq queries, but is also called in the legacy code (ie during the foreach(object o in collection) and foreach(Test in Collection).

Is there any difference between the old way of iterating through the collection and this new way assuming all the items in the collection are of type Test? I am aware that adding the IEnumerator method will cause the program to throw an exception if it finds any types other than Test, but want to know if I have overlooked anything.

like image 298
sgmoore Avatar asked Sep 23 '09 20:09

sgmoore


2 Answers

Since you are in 2.0 (or above), perhaps just inherit from Collection<T>?

public class TestCollection : Collection<Test> {
    // your extra code here
}

Then you get IList<T>, ICollection<T>, IEnumerable<T> for free, and virtual methods that you can override to put your stamp on the behaviour.

like image 199
Marc Gravell Avatar answered Nov 09 '22 16:11

Marc Gravell


No, you will see identical results and only experience a single extra level of indirection (as the new GetEnumerator method simply calls the existing GetEnumerator method and streams its output).

like image 42
Andrew Hare Avatar answered Nov 09 '22 15:11

Andrew Hare