I have the following code where I'm printing values before the Main()
method gets called by using a static constructor. How can I print another value after Main() has returned, without modifying the Main()
method?
I want output like:
1st
2nd
3rd
The "base" code I use:
class Myclass
{
static void Main(string[] args)
{
Console.WriteLine("2nd");
}
}
I added a static constructor to Myclass for displaying "1st"
class Myclass
{
static Myclass() { Console.WriteLine("1st"); } //it will print 1st
static void Main(string[] args)
{
Console.WriteLine("2nd"); // it will print 2nd
}
}
Now What i need to do to is to print 3rd without modifying the Main()
method. How do I do that, if it is at all possible?
Continuing on your same thought with the Static constructor, you can use the AppDomain.ProcessExit Event leaving Main() untouched.
class Myclass
{
// will print 1st also sets up Event Handler
static Myclass()
{
Console.WriteLine("1st");
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
}
static void Main(string[] args)
{
Console.WriteLine("2nd"); // it will print 2nd
}
static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("3rd");
}
}
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