Last post Feb 15, 2014 06:23 PM by Paul Linton
Feb 15, 2014 06:25 AM|TheNutCracker|LINK
The code at this link
looks rather odd to me. I have posted a portion of it that has me perplexed below:
public Person Current
throw new InvalidOperationException();
So the order of operations in the example code are:
1. foreach() loop calls IEnumerator.Current explicitly
2 IEnumerator.Current calls regular Current property returning a Person object
3.IEnumerator.Current returns this Person object as a regular System.Object object and assigns it to the range variable
4. The range variable automatically casts(or at least interprets) the returned object as a Person object
What is with all the back and forth in this example - your an object, wait your a Person, no your back to an object, now you are a Person???
Is this the whackiest example of code I have stumbled upon or is it me...am I the one who is at fault...am I the one who needs counseling?
Feb 15, 2014 08:04 AM|AidyF|LINK
IEnumerator is a .net interface but it has to work for any collection so it's Current property returns an object and the calling code has to know what type that object really is. It has to rerturn object as that is what the interface is defined as
When you implement an interface you have to implement it exactly
IEnumerator dates back to older versions of .net before generics. Now there is a generic version, IEnumerator<T> which can be strongly typed.
Feb 15, 2014 06:23 PM|Paul Linton|LINK
Yes it is whacky. But it is how we did things in the olden days. Before generics we had this kind of crazy stuff. You should not use this. Someone maintaining old code may need to understand this sort of thing so the example is relevent to them.
For new code (that is anything written since about 2006) you should use the generic iterators.