[Gtk-sharp-list] Enumerable TreeModel Problems

Michael Hutchinson m.j.hutchinson at gmail.com
Mon Sep 29 17:08:29 EDT 2008


On Mon, Sep 29, 2008 at 4:40 PM, Iggy <iggy.ma at gmail.com> wrote:
> So i have a new class that inherits from TreeStore, and I'd like to
> implement IEnumerable so you can foreach through it. The
> implementation code is pretty simple. The problem is that this code
> works perfect the first time, but if it is run through again it gets
> Object Reference Not Found errors. It seems like once this foreach
> gets done the TreeStore loses everything in it, or its almost as if
> its made into a null TreeStore. I can't for the life of me figure out
> why it loses everything when the foreach is done...
>
>
> [code]
> public class EnumerableTreeStore : TreeStore, IEnumerable, IEnumerator

Why is your IEnumerable the IEnumerator instance too? That's a really
strange implementation of this pattern.

I suggest using yield return to generate the iterator automatically. A
simple (flat) implementation:

public IEnumerator GetEnumerator()
{
    TreeIter iter;
    if (!GetIterFirst (out iter))
        yield break;
    do {
        yield return iter;
    } while (IterNext (ref iter));
}

You can do even neater things with C# 3 and extension methods. For example:

public static IEnumerable<TreeIter> EnumerateIters (this TreeStore store)
{
    TreeIter iter;
    if (!store.GetIterFirst (out iter))
        yield break;
    do {
        yield return iter;
    } while (store.IterNext (ref iter));
}

public static IEnumerable<T> EnumerateValues<T> (this TreeStore store,
int column)
{
    return from TreeIter iter in store.EnumerateIters () select (T)
store.GetValue (column);
}

It'd be nice to start a Gtk.Rocks assembly for this kind of stuff :-)


BTW, I think your bug is that GetEnumerator() needs to call Reset ().
This problem stems from not returning a new enumerator.

-- 
Michael Hutchinson
http://mjhutchinson.com


More information about the Gtk-sharp-list mailing list