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.
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'.
'\r' is the carriage return character.
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.
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.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With