frenchie
frenchie

Reputation: 51927

What happens to objects instantiated inside static methods?

I have a static object that looks somewhat like this:

public static class MyStaticObject
{    
   public static void SomeMethod()
   {
       MyObject TheObject = new MyObject();    

       //some long runnning tasks
   }
}

As you can see, when SomeMethod() runs, it creates a MyObject. What happens to this instantiated object after the method that created it returns? If SomeMethod() is called again while it's already executing in response to a previous method call, is there going to be a concurrency problem or does each method call instantiate its own MyObject?

Upvotes: 0

Views: 1541

Answers (1)

AlexD
AlexD

Reputation: 32566

TheObject is just a local variable, and it behaves the same way regardless of the fact if the method is static or not.

So after the method returns, the object (if there are no more references to it) is ready for the garbage collector.

And in case of recursion, just another local variable will be created.

If you have C/C++ background, the TheObject is not a static variable in C/C++ terms.

Upvotes: 3

Related Questions