namespace TestApp
{
class Program
{
public Program()
{
var breakpoint1 = 0;
}
static void Main(string[] arguments)
{
var breakpoint2 = 0;
}
}
}
breakpoint 1
is never hit , but it hits breakpoint 2
always? Main()
?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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With