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.

3
  • Are you accessing the class at all? Commented Feb 4, 2016 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. Commented Feb 4, 2016 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. Commented Feb 4, 2016 at 14:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So I guess I do need a method after all and by calling the method it would also cause the constructor to be called?
Method, constant, property, field... it could be anything.
Cool, that makes sense to me. I mistakenly thought that making it static would be enough. Thanks. (I have to wait to accept).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.