Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

How to execute a method Once during Runtime on c#

Is there a possibility to prevent method execution more than once during Run-time of an Instance without using an external Attribute ?

I hope i was clear ! Bests

Upvotes: 2

Views: 11186

Answers (5)

FIre Panda
FIre Panda

Reputation: 6637

public class TestClass
{
static private bool _isExecutedFirst = false;

public void MethodABC()
{
if(!_isExecutedFirst)
_isExecutedFirst = true;
else
throw Exception("Method executed before");
/////your code

} 
}

Hope this help

Upvotes: 3

Matt Mitchell
Matt Mitchell

Reputation: 41823

No, there is no way to prevent method execution without storing some kind of 'state' saying the method has already been executed.

One way of doing this is a "guard" / check at start:

private bool AExecuted = false;
public void A()
{
    if (AExecuted)
       return;
    else
       AExecuted = true;

    /* Your code */
}

Upvotes: 0

RedDeckWins
RedDeckWins

Reputation: 2121

Try using a static constructor

Upvotes: 3

Orochi
Orochi

Reputation: 397

Yes, you can use like this

void method(args)
{
    static int a;
    if(a != 0)
    {
        return;
    }
    // body of method and 
    a++;
}

reason being this static a will not be copied to activation records of the function calls and all will share only one a.

I hope this resolve your question.

Upvotes: 0

Jamiec
Jamiec

Reputation: 136104

sure, with a flag to indicate whether a method on an instance has been run.

public class RunOnceMethod
{
  private bool haveIRunMyMethod = false

  public void ICanOnlyRunOnce()
  {
    if(haveIRunMyMethod)
      throw new InvalidOperationException("ICanOnlyRunOnce can only run once");

    // do something interesting

    this.haveIRunMyMethod = true;
  }
}

Upvotes: 0

Related Questions