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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sanjeeb LenkaRank #301 · 8.3K reputationPosted Sep 5, 2013, 4:20 AM EDT
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();
}
}
}
VulpesRank #55 · 29.2K reputationPosted Sep 5, 2013, 4:12 AM EDT
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.
VulpesRank #55 · 29.2K reputationPosted Sep 5, 2013, 4:21 AM EDT
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.
Posted Sep 5, 2013, 6:43 AM EDT
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.
VulpesRank #55 · 29.2K reputationPosted Sep 5, 2013, 7:31 AM EDT
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!
Sanjeeb LenkaRank #301 · 8.3K reputationPosted Sep 5, 2013, 7:38 AM EDT
Posted Sep 5, 2013, 12:23 PM EDT