16
namespace TestApp
{
  class Program
  {
    public Program()
    {
      var breakpoint1 = 0;
    }

    static void Main(string[] arguments)
    {
      var breakpoint2 = 0;
    }
  }
}
  1. Why breakpoint 1 is never hit , but it hits breakpoint 2 always?
  2. And is there a way to execute the default constructor before entering Main() ?
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
AstroSharp
  • 1,872
  • 2
  • 22
  • 31

4 Answers4

23

The Main method is executed without an instance of the Program class, which is possible because it is a static method. Static methods are methods that can be called without the need to construct/instantiate an object from the class. They can be called directly on the Class itself like this:

Program.Main(new string[0]); 

// executes the Main static method on Program class 
// with empty string array as argument

The constructor is not a static method, to hit that breakpoint you need to instantiate the Program class, like this:

static void Main(string[] arguments)
{
  var breakpoint2 = 0;
  new Program(); // breakpoint1 will be hit
}

Alternatively you can make the constructor static, though admittedly it is not really that useful from a testability standpoint and also implies that you're going to have static variables (that are globally available):

static Program() {
    var breakpoint1 = 0; 
    // breakpoint will be hit without an instance of the Program class
}

You can read more about static methods here.

Community
  • 1
  • 1
Spoike
  • 119,724
  • 44
  • 140
  • 158
20

You are not instantiating the class. You are running a static Main() method. The run time will load the class and invoke the Main() method .It doesn't need an instance of the class to invoke the Main() method. Constructor will run when you construct(instantiate) an object.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
9

Your method is static: it will run without an instance of the class existing. Your constructor is not: it is only executed when you create an instance of the class (that is, when you write new Program()).

In order to hit your breakpoint, most likely you want to change your constructor to be static Program() instead.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
  • Access modifiers aren't allowed on static constructors, i.e. it would be simply `static Program(){}`, not `public static Program(){}` – Tim M. Jun 05 '13 at 16:56
  • 1
    +1 for mention of static constructors, though there's no need for public since it's called implicitly. http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.80).aspx – Mark Brackett Jun 05 '13 at 16:56
  • Thanks for the correction - copying and pasting without due attention! – Dan Puzey Jun 05 '13 at 21:50
4

The entry point to your program is equivalent to calling TestApp.Program.Main(args). The Program class doesn't get instantiated.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173