Reputation: 7724
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?
Upvotes: 2
Views: 88
Reputation: 37020
Another way you could solve this is to maintain a list of strings that represent the methods that have been called. The strings don't even have to be the method name, they just need to be unique to each method.
Then you can have a helper method called ShouldIRun
that takes in the function's unique string and checks to see if it exists in the list. If it does, then the method returns false
, and if it doesn't, then the method adds the string to the list and returns true
.
The nice thing here is that you don't have to maintain a bunch of state variables, you can use this with as many methods as you want, and the methods themselves don't need any complicated logic - they just ask the helper if they should run or not!
public class Program
{
private static List<string> CalledMethods = new List<string>();
static bool ShouldIRun(string methodName)
{
if (CalledMethods.Contains(methodName)) return false;
CalledMethods.Add(methodName);
return true;
}
// Now this method can use method above to return early (do nothing) if it's already ran
static void OnlyCalledOnce()
{
if (!ShouldIRun("OnlyCalledOnce")) return;
Console.WriteLine("You should only see this once.");
}
// Let's test it out
private static void Main()
{
OnlyCalledOnce();
OnlyCalledOnce();
OnlyCalledOnce();
GetKeyFromUser("\nDone! Press any key to exit...");
}
}
Output
Upvotes: 2
Reputation: 6514
As already stated, you can use this:
private bool isExecuted = false;
void DoesNothing(){}
void OnlyCalledOnce(){
if (!isExecuted)
{
isExecuted = true;
//lines of code
DoesNothing();
}
}
If you have multiple threads etc, you can do a lock(object) ..
Upvotes: 0
Reputation: 1720
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;
}
}
Upvotes: 2
Reputation: 975
What's your problem with this?
void DoesNothing()
{
}
void OnlyCalledOnce()
{
DoesNothing();
}
It will run DoesNothing() once you run OnlyCalledOnce()
Upvotes: -1
Reputation: 10929
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.
Upvotes: 5