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

Share:
10,435
Rosmarine Popcorn
Author by

Rosmarine Popcorn

Updated on June 04, 2022

Comments

  • Rosmarine Popcorn
    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
    Matt Mitchell almost 13 years
    You can't declare a variable as static within a method. Also the question asked for once per instance.
  • Matt Mitchell
    Matt Mitchell almost 13 years
    How would that help exactly? How would a static constructor test when the method is run or prevent method subsequent method execution?
  • Naui Monclús
    Naui Monclús almost 13 years
    The 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
    jimjim almost 13 years
    it 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
    Naui Monclús almost 13 years
    shouldn't AExecuted be static ?
  • Jamiec
    Jamiec almost 13 years
    Love 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
    Orochi almost 13 years
    duh... i thought he's asking for C++ one
  • Veeru
    Veeru almost 13 years
    I didn't ask for these powers ;)
  • Matt Mitchell
    Matt Mitchell almost 13 years
    @AB Kolan - no? He wants per instance guards.
  • Matt Mitchell
    Matt Mitchell almost 13 years
    A static constructor would limit to one execution per class. The OP asked for one execution per instance.
  • Matt Mitchell
    Matt Mitchell almost 13 years
    This is one run per class - the OP asked for one run per instance.