Q:

Running a piece of code just once in a class

I need to attach an event handler to an object, and I placed this code on a button click event. However, I noticed that this will cause the same event to attach multiple times with each click.
Is there a way to run a piece of code on class creation? The class in question is a static class btw.
I can do something like:
if (bool == false)
{
attach event handler;
bool = true;
}

Just not sure if this is the right way to do it. Thanks.

A:

You use a constructor - it will run on class creation.

Constructors are class methods that are executed when an object of a class or struct is created. They have the same name as the class or struct, and usually initialize the data members of the new object.

For static classes, use static constructors:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

A:

There are static constructors, that are (in principle) only run once per class.
Something like this:
public static class MyStaticClass
{
   public static int MyStaticProperty;

   //no accessors required, as this is never explicitly invoked
   static MyStaticClass() //no parameters either
   {
      MyStaticProperty = 100;
   }
}
....
//writes: 100
Console.WriteLine(MyStaticClass.MyStaticProperty);

However, if a constructor won't do it, because you have some parameters that need to be set, or there are some prerequisite steps that need to be done, I would indeed recommend a private boolean check, as you have done.

