Jon Skeet said:
Yes you do. The compiler has created them for you.
No, the foreach statement *cannot* work without MoveNext() and
Current.
Irrelevant - if you use "yield return" style code, the compiler will
generate a lot of stuff for you.
No, I understand the code - but I don't think you understand what the
compiler is doing for you. I *strongly* recommend that you run ildasm
or Reflector on your code to see what's being generated.
See
http://www.yoda.arachsys.com/csharp/csharp2/iterators.html for
some more information on this, by the way.
Jon
thanks Jon, thats quite a usefully concise info about what ive been doing,
I think I at least understand fairly well whats going on at the code level
now.
the 'yield return expresion' does make for a bit of confusion over flow of
control at first.
I think I understand that movenext is like moving to the next statemnt in
the GetEnumerator function if yield is used, and current would be like
storing the state information of the functions stack.
although I had assumed it just put the code inline or something,
and put the code inside the foreach block at each yeild statement.
Ive not tried using reflection or looking at the code directly,
im not sure I want to atm lol, I might not understand or like what I see.
maybe its not as fast as I would like if its actually storing the stack
info,
but then this isnt a method that will be used intensivly to access the list.
my original implementation was written partly in assembler many years ago
when CPU power wasnt so plentifull.
before that I also had a microcode version for a bit slice processor,
before content addressable ram made it obsolete.
heres the minimum code wich just builds up the list and dumps it to the
console.
its hardly finished, rebalancing wil be done when excessive time spent in
searching is detected.
:-------
using System.Collections.Generic;
namespace WindowsApplication1
{
public class stree<DType>
{
public class node
{
public node(DType x)
{
val=x;
}
public IEnumerator<DType> GetEnumerator() // recursive
iterator.
{
if (low != null)
foreach (DType x in low)
yield return x;
yield return val;
if (high != null)
foreach (DType x in high)
yield return x;
}
public DType val;
public node high,low;
}
public System.Collections.Comparer compare =
System.Collections.Comparer.DefaultInvariant;
public node root;
public void Add(DType x)
{
Add(ref root, x);
}
public bool Add(ref node p,DType x)
{
if (p == null)
{
p = new node(x);
return true;
}
int r = compare.Compare(x, p.val);
if (r > 0)
return Add(ref p.high, x);
if(r<0)
return Add(ref p.low, x);
return false;
}
public IEnumerator<DType> GetEnumerator()
{
if(root!=null)
foreach (DType x in root)
yield return x;
}
}
}
main()
{
stree<double> tree = new stree<double>();
tree.Add(4.1);
tree.Add(4.3);
tree.Add(4.9);
tree.Add(2.1);
foreach (double y in tree)
System.Console.WriteLine(y);
}
Colin =^.^=