I’m trying to do this in a class extending another class, which implements IEnumerable<T>:
public override IEnumerator<T> GetEnumerator(){
foreach (var item in base){
// Some logic here
yield return item;
// Some more logic here
}
}
However this fails with compile error stating that “base” is used incorrectly.
I want to inherit all behaviour of the parent class except of inserting some “virtual” items into the enumerated collection and skipping some other items.
I worked around this by manually manipulating the enumerator (essentially doing what foreach expands to except calling GetEnumerator on base instead of this). But this doesn’t result in exactly the most straightforward code.
So my question is: Can this be done with foreach?
No, it can’t be done with foreach.
There is big difference between
thisandbaseaccess in C#. When you usethiskeyword, it is classified as a value (type of value is the instance type of class where usage occurs). Butbasekeyword is never treated as a value. It could be part of base-access expression, which used to access base class members that are hidden by similarly named members in the current class:So, via
basekeyword you can only access members of base class. But it is not treated as value of base type, and it could not be part of expression where value used (e.g. casting, foreach statements, etc).And only valid approach to do what you want is accessing members of base class: