How to break a program before called to Main()?
This question ask in interview... please tell me...
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sanjeeb LenkaPosted Sep 5, 2013, 8:20 AM
try this console program and check:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace IfExample
{
class braekcs
{
static braekcs()
{
Console.WriteLine("Test123");
Thread.Sleep(5000);//it will pause the program for 5 sec
Environment.Exit(1); //after that it kills the process and main will not execute
}
static void Main(string[] args)
{
Console.WriteLine("Test111");
Console.ReadLine();
}
}
}
Posted Sep 5, 2013, 4:23 PM
Sanjeeb LenkaPosted Sep 5, 2013, 11:38 AM
VulpesPosted Sep 5, 2013, 11:31 AM
This applies even if the class concerned is the one which contains the Main() method.
So, in Sanjeeb's example, breakcs's static constructor will run before the Main() method is called by the system.
You should therefore be able to step through the code in VS until the following line is reached:
Environment.Exit(1);
This will cause the current process to be killed stone dead and so the Main() method will never be called :)
Incidentally, this forum seems to have suddenly lost the ability to edit one's posts - the Edit button has disappeared!
I said in my previous post that calling 'return' from the static constructor would prevent the Main() method from being called. That, of course, is wrong - only Environment.Exit(1) or something similar such as System.Diagnostics.Process.GetCurrentProcess().Kill() will do that.
EDIT: The Edit button's back now!
Posted Sep 5, 2013, 10:43 AM
Programme produced by Sanjeeb Lenka seems violating usual norms. Whether you use F11 or F5 key programme is executing and producing console output and you can't see the step by step execution of the programme.
Please explain the reason.
VulpesPosted Sep 5, 2013, 8:21 AM
If you include a static constructor in the same class as the Main() method and call 'return' (or one of the other options in my first post) from the static constructor that will prevent the Main method from running at all.
VulpesPosted Sep 5, 2013, 8:12 AM
However, you can prevent it from running to completion by either calling 'return' (or 'return 1' if you're using the version of Main() which returns an int) or by calling Environment.Exit(1) which kills the process.