Is there a way in C# to call a method just once like in the jQuery "one" method?

The jQuery example is an event handler, and once the event handler has been called it is removed from the element. The equivalent in C# for (eg.) an button click event would be

myButton.Click += new EventHandler(MyEventHandler)

void MyEventHandler(object sender, EventArgs e)
{
  Console.Write("hello");
  ((Button)sender).Click -= new EventHandler(MyEventHandler);
}

In this way, only the first click of the button would yield the Console Write.


I can't imagine why do something like that, but if you really do it and if you want it universal for any method, you can do this:

void Main() {
    var myFoo = callOnlyOnce(foo);
    myFoo();
    myFoo();
    myFoo();

   var myBar = callOnlyOnce(bar);
   myBar();
   myBar();
   myBar();
}

void foo(){
  Console.Write("hello");
}
void bar() { Console.Write("world"); }


Action callOnlyOnce(Action action){
    var context = new ContextCallOnlyOnce();
    Action ret = ()=>{
        if(false == context.AlreadyCalled){
            action();
            context.AlreadyCalled = true;
        }
    };

    return ret;
}
class ContextCallOnlyOnce{
    public bool AlreadyCalled;
} 

Why do you want a library when you could just do something like this:

private bool wasExecuted = false;

public void foo(){
  if (!wasExecuted) {
     Console.Write("hello");
     wasExecuted = true;
  }
}

Tags:

C#