Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i print any value after Main() method gets called?

Tags:

c#

.net

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?

like image 672
Neo Avatar asked Aug 09 '11 06:08

Neo


1 Answers

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");
        }
    }
like image 129
nageeb Avatar answered Sep 25 '22 02:09

nageeb