Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I wish to know if there is a way to execute code in C# just once, like "one" in jquery:

$("#foo").one("click", function() { alert("This will be displayed only once."); });

What I would like to do is the following:

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

then

foo();
foo();
foo();

and the output result must be

hello

I´m looking for a library and not just using flags attributes.

like image 787
Müsli Avatar asked Apr 08 '11 16:04

Müsli


People also ask

Does \n work in C?

CAUSE. In most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'.

What does \r mean C?

'\r' is the carriage return character.

Is C programming difficult?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.

What is the fastest way to learn C?

Get started with C. Official C documentation - Might be hard to follow and understand for beginners. Visit official C Programming documentation. Write a lot of C programming code - The only way you can learn programming is by writing a lot of code.


2 Answers

I know this is old news... but here is a Functional approach to the question that someone might find useful:

    public static Action<T> Once<T>(Action<T> action )
    {
        return (arg) =>
        {
            action?.Invoke(arg);
            action = null;
        };
    }

Then you can generate a function that will only do the meat of the work one time:

    var writeNumberToConsole = Once<int>( Console.WriteLine );
    writeNumberToConsole(1); // "1"
    writeNumberToConsole(2); -> //nothing
    writeNumberToConsole(3); -> //nothing
like image 174
bluetoft Avatar answered Sep 18 '22 08:09

bluetoft


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;
} 
like image 27
TcKs Avatar answered Sep 18 '22 08:09

TcKs