Your problems are two fold.
- Lifespan of the variable. A local variable only lives in the block it is defined in. Thus you defined testObj inside the foreach loop. Thus it only lives through one iteration of the block and ends to live at the end of the loop. The next iteration has a new testObj then.
Thus
object testObj
foreach(var test in Tests)
{
testObj = new object();
//Do something with the object
}
Would solve this as testObj is defined outside the loop and thus regardless of iteration lives with the values set.
Then
- You always set it anew. If you set a variable to a new value the old value is overwritten with the new value. Thus you would have to use lists, arrays, ... if you want to save every testObj you create (or use 1 variable for each testObj but normally that is something only complete beginners do. Only mentioning it for completeness sake and to mention that it is something not to do as it will enlarge your overhead greatly).
So you could do:
List testObjList = new List();
foreach (var tests in Tests)
{
testObjList.Add(new object());
// Or alternatively object testObj = new object(); testObjList.Add(testObj);
}
If you add it directly into the list (Add(new object)) you can acces it by using testObjList[testObjList.Count - 1]
(count-1 as indexes begin with 0 and not 1). This is then the same as when you use testObj of the second variant.
Edit:
For using them inside threads and then eliminating these objects you have 2 options.
1.) The object does not have any functionality for dispose then your original code is fine there:
foreach(var test in Tests)
{
object testObj = new object();
//Do something with the object
}
The object is lost when the block ends BUT the garbage collector decides when it is really deleted (there are some exceptions like images where it can be that you need to do special operations in order to be able to delete them though).
If your object is of a specific class (lets call it myobject to not confuse it with the normal object) that has a dispose functionality it offers:
foreach(var test in Tests)
{
using (myObject testObj = new myObject())
{
//Do something with the object
}
}
This means that the myObject object is only living within the using block and additionally when the block ends (even if through an exception) the dispose part is executed, which should make sure that the garbage collector is able to free the memory.