Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointing a function to another

Suppose I have two functions:

void DoesNothing(){}

void OnlyCalledOnce(){
    //lines of code
}

Is it possible to call OnlyCalledOnce and it actually run DoesNothing ? I imagine something like this:

void DoesNothing(){}

void OnlyCalledOnce(){
    //lines of code
    OnlyCalledOnce = DoesNothing;
}

and after that last line, whenever I called OnlyCalledOnce it would run DoesNothing.

Is it possible?

like image 893
Daniel Avatar asked Feb 15 '26 03:02

Daniel


2 Answers

You can simply return early in OnlyCalledOnce like this: (assuming your DoesNothing example literally does nothing - it isn't needed)

bool initialized = false;

void OnlyCalledOnce()
{
    if (initialized) return;

    // firsttimecode
    initialized = true;
}

The initialized variable will be true after first run.

like image 107
Poul Bak Avatar answered Feb 17 '26 16:02

Poul Bak


Did you try to use delegate?

class Program
{
    private static Action Call = OnlyCalledOnce;

    public static void Main(string[] args)
    {
        Call();
        Call();
        Call();
        Console.ReadKey();
    }

    static void DoesNothing()
    {
        Console.WriteLine("DoesNothing");
    }

    static void OnlyCalledOnce()
    {
        Console.WriteLine("OnlyCalledOnce");
        Call = DoesNothing;
    }
}
like image 30
KozhevnikovDmitry Avatar answered Feb 17 '26 15:02

KozhevnikovDmitry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!