Enforcing an "end" call whenever there is a corresponding "start" call

Posted by Jeff Meatball Yang on Stack Overflow See other posts from Stack Overflow or by Jeff Meatball Yang
Published on 2010-04-27T21:56:27Z Indexed on 2010/04/27 22:03 UTC
Read the original article Hit count: 251

Filed under:
|

Let's say I want to enforce a rule:

Everytime you call "StartJumping()" in your function, you must call "EndJumping()" before you return.

When a developer is writing their code, they may simply forget to call EndSomething - so I want to make it easy to remember.

I can think of only one way to do this: and it abuses the "using" keyword:

class Jumper : IDisposable {
    public Jumper() {   Jumper.StartJumping(); }
    public void Dispose() {  Jumper.EndJumping(); }

    public static void StartJumping() {...}
    public static void EndJumping() {...}
}

public bool SomeFunction() {
    // do some stuff

    // start jumping...
    using(Jumper j = new Jumper()) {
        // do more stuff
        // while jumping

    }  // end jumping
}

Is there a better way to do this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about business-logic