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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With