If I call "Method()", what happens to the MyClass object that was created in the process?
It gets created on the GC heap. Then a reference to its location in the heap is placed on the stack. Then the call to AnotherMethod happens. Then the object's ToString method is called and the result is printed out. Then AnotherMethod returns.
Does it still exist in the stack after the call, even though nothing is using it?
Your question is ambiguous. By "the call" do you mean the call to Method, or AnotherMethod? It makes a difference because at this point, whether the heap memory is a candidate for garbage collection depends upon whether you compiled with optimizations turned on or off. I'm going to slightly change your program to illustrate the difference. Suppose you had:
void Method()
{
AnotherMethod(new MyClass());
Console.WriteLine("Hello world");
}
With optimizations off, we sometimes actually generate code that would be like this:
void Method()
{
var temp = new MyClass();
AnotherMethod(temp);
Console.WriteLine("Hello world");
}
In the unoptimized version, the runtime will actually choose to treat the object as not-collectable until Method returns, after the WriteLine. In the optimized version, the runtime can choose to treat the object as collectible as soon as AnotherMethod returns, before the WriteLine.
The reason for the difference is because making object lifetime more predictable during debugging sessions often helps people understand their programs.
Or does it get removed immediately?
Nothing gets collected immediately; the garbage collector runs when it feels like it ought to run. If you need some resource like a file handle to be cleaned up immediately when you're done with it then use a "using" block. If not, then let the garbage collector decide when to collect memory.
Do I have to set it to null to get GC to notice it quicker?
Do you have to set what to null? What variable did you have in mind?
Regardless, you do not have to do anything to make the garbage collector work. It runs on its own just fine without prompting from you.
I think you're overthinking this problem. Let the garbage collector do its thing and don't stress about it. If you're having a real-world problem with memory not being collected in a timely manner, then show us some code that illustrates that problem; otherwise, just relax and learn to love automatic storage reclamation.