COMMUNITY

Auto-dispose on closed scope?

C# (and other languages?) has the helper using statement that automatically calls Dispose, it’s a nice safety to have around. Does Haxe have something similar?

I ask because I’m having to deal with some native C# Enumerators and the code gets a bit messy, I could wrap them with a custom Haxe Iterable but C# wants the Dispose call.

Here’s the basic code in Haxe to talk to a C# Enumerator:

var csEnum = nativeEnumerable.GetEnumerator();
while(csEnum.MoveNext()) {
    var value = csEnum.Current;
    // Do stuff
}
csEnum.Dispose();

Easy to wrap so Haxe can use a standard for loop on it, but the only issue is calling Dispose at the end.

No response, so probably a ‘no’ on auto-dispose. This is mostly important for me when working with database connections, so no matter what happens (exceptions/etc) within the scope the session is ‘disposed’, transaction rolled back and disconnected.

If anyone comes across this post looking for a C# to Haxe iterable wrapper, here’s what I ended up with (easy to use via extension method):

class IEnumerableIterator<T> {
    var enumerator:cs.system.collections.generic.IEnumerator_1<T>;
    var hasNextBool = false;
    var nextCalled = false;
    public function new(enumerable:cs.system.collections.generic.IEnumerable_1<T>) {
        enumerator = enumerable.GetEnumerator();
    }

    public function hasNext():Bool {
        if(!nextCalled) {
            hasNextBool = enumerator.MoveNext();
            nextCalled = true;
        }
        return hasNextBool;
    }

    public function next():T {
        hasNext();
        nextCalled = false;
        return enumerator.Current;
    }
}

Umm… not to sound stupid here, but … does this call Dispose()? If so, how?

The first thing that came to mind:

    public function hasNext():Bool {
        if(!nextCalled) {
            hasNextBool = enumerator.MoveNext();
            if (hasNextBool  == false) enumerator.Dispose();
            nextCalled = true;
        }
        return hasNextBool;
    }

(Post Deleted)

I gave up on calling Dispose so I could move on with the project, it doesn’t appear to be required by Enumerators in C#. I do want to auto-dispose things such as database sessions, but I haven’t found a good solution for that.

@RedHeadEatBread thanks for the idea!