If you mean the object ( new Foo(i);
), then my understanding is that no: this is never allocated on the stack; however, it will die in generation zero, so will be very efficient to collect. I don't profess to know every dark and dank corner of the CLI, but I am not aware of any scenario in C# that would lead to a managed reference-type being allocated on the stack (things like stackalloc
don't really count, and are highly specific). Obviously in C++ you have a few more options, but then it isn't a managed instance.
Interestingly, on MonoTouch/AOT it might be collected immediately, but that is not the main CLI VM (and is for a very specific scenario).
As for the variable - that will usually be on the stack (and re-used for each loop iteration) - but it might not be. For example, if this is an "iterator block", then all the non-removed local-variables are actually fields on the compiler-generated state-machine. More commonly, if the variable is "captured" (into an anonymous method or lambda expression, both of which form closures), then the variable is transformed into a field on the compiler-generated capture-context, and is separate per loop iteration (since foo
is declared inside the loop). This means that each is separate on the heap.
As for i
(the loop variable) - if that gets captured, it gets even more interesting
- in C# 1.2 captures didn't exist, but by the spec the loop-variable is technically per-iteration
- in C# 2.0 to 4.0, the loop variable is shared (causing the infamous capture/foreach common question)
- in C# 5.0 and above the loop variable is per-iteration again
this only makes a difference when the variable is captured, but changes the semantics of exactly how it manifests on the capture-context