How to execute a method Once during Runtime on c#
10,435
Solution 1
Try using a static constructor
Solution 2
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
Author by
Rosmarine Popcorn
Updated on June 04, 2022Comments
-
Rosmarine Popcorn almost 2 years
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
-
Matt Mitchell almost 13 yearsYou can't declare a variable as static within a method. Also the question asked for once per instance.
-
Matt Mitchell almost 13 yearsHow would that help exactly? How would a static constructor test when the method is run or prevent method subsequent method execution?
-
Naui Monclús almost 13 yearsThe method can be enclosed in a static ctor of the class & "The static constructor for a non-generic class executes at most once in a given application domain" copied verbatim from ECMA C# spec - en.csharp-online.net/ECMA-334%3A_17.11_Static_constructors
-
jimjim almost 13 yearsit works by // Static constructor is called at most one time, before any // instance constructor is invoked or member is accessed. and a value can be set that is changed when the method is called. next time the method tries to execute first it checks the value.
-
Naui Monclús almost 13 yearsshouldn't AExecuted be static ?
-
Jamiec almost 13 yearsLove it. OP specifies "prevent method execution more than once during Run-time of an Instance" and then marks an answer talking about static constructor as the answer. You need to be a mindreader sometimes.
-
Orochi almost 13 yearsduh... i thought he's asking for C++ one
-
Veeru almost 13 yearsI didn't ask for these powers ;)
-
Matt Mitchell almost 13 years@AB Kolan - no? He wants per instance guards.
-
Matt Mitchell almost 13 yearsA static constructor would limit to one execution per class. The OP asked for one execution per instance.
-
Matt Mitchell almost 13 yearsThis is one run per class - the OP asked for one run per instance.