Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the default constructor of class Program is Never executed?

Tags:

c#

.net

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() ?
like image 716
AstroSharp Avatar asked Jun 05 '13 16:06

AstroSharp


2 Answers

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.

like image 174
Spoike Avatar answered Oct 23 '22 23:10

Spoike


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.

like image 26
AllTooSir Avatar answered Oct 23 '22 23:10

AllTooSir