2

I'm writing a Console application in C#. When the application is run I need it to check a few things before doing any work such as whether certain settings and directories exist. I have a static class for this stored in Logging.cs and I have put the checks in the constructor for this class but it never seems to get called.

Here's a very basic example:

Program.cs

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine("Started application");
        Console.ReadKey(); // Stops the application exiting so I can read the output
    }
}

Logging.cs

internal static class Logging
{
    static Logging()
    {
        // The checks are all here, for the demo we'll just use WriteLine
        Console.WriteLine("Logging constructor");
    }
}

Expected console output:

Started application
Logging constructor <-- This line never appears

I know I could create a static method inside the Logging class called DoStartupChecks and call it from Main in Program.cs, but I want to understand what I've done wrong here. Maybe the answer is to create the method and call it but I want to understand why the above example is wrong first.

Equalsk
  • 7,954
  • 2
  • 41
  • 67
  • Are you accessing the class at all? – Lasse V. Karlsen Feb 04 '16 at 14:13
  • Static constructor gets called the first time the class is used, not when your program is loaded. So your example would indeed not cause the constructor to be called. – Mark Feb 04 '16 at 14:13
  • OK that makes sense. I thought that making it static would create an instance and therefore call the constructor. This makes more sense. Thanks. – Equalsk Feb 04 '16 at 14:17

1 Answers1

5

The static constructor is called when a class is referenced the very first time, e.g. by calling any of its members, by creating an instance of it or by calling a method on it.

Thus you have to write something like this:

private static void Main(string[] args)
{
    Logging.DoSomething();
    Console.WriteLine("Started application");
    Console.ReadKey(); // Stops the application exiting so I can read the output
}

From MSDN:

It [the static constructor] is called automatically before the first instance is created or any static members are referenced.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111