Reputation: 10967
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
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
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
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
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