C# Static

  • Thread starter Thread starter Coder Coder
  • Start date Start date
C

Coder Coder

Hello,
Is it possible in C# to have the following.

public class Foo
{
static
{
}

public Foo ()
{
}
}

Having a section of code which is static and is executed at the
startup of the program.

- Thanks
 
Yes, it is, with a slight adjustment.

It should be
static Foo()
{
}

and it is a static constructor when the class is touched for the first time.

Miha
 
Thus spake Coder Coder:
Hello,
Is it possible in C# to have the following.

Almost. Change static {} to static Foo() {} and you're in business.
Having a section of code which is static and is executed at the
startup of the program.

Subtle difference: static constructors are called prior to the
initialization of the first instance of that class or the first use of a
static method, not upon program startup.

Check the help on "static constructors" for detailed explanations.
 
Coder Coder said:
Is it possible in C# to have the following.

public class Foo
{
static
{
}

public Foo ()
{
}
}

Having a section of code which is static and is executed at the
startup of the program.

It's not executed at the start of the program - it's executed when the
type is first initialized (ie immediately prior to its first use).
 
I'd just like to add to what's gone before that the static constructor
(which is what it's called) is run after the initialization of any static
variables that have explicit initializations.

Tom Dacon
Dacon Software Consulting
 
Back
Top