I came across the following C# function:
void SomeMethod(List<ISomeInterface> inputObjects)
{
IList<ISomeInterface> newListOfObjects = null;
if (inputObjects != null)
{
//create a new list
newListOfObjects = new List<ISomeInterface>();
//copy the input parameter into the new list
foreach (ISomeInterface thing in inputObjects)
{
newListOfObjects.Add(thing);
}
}
//send an event to another module with the new list as parameter
DelegateHandler.AsyncInvoke(this.SomeEvent, newListOfObjects);
}
My questions are: is it necessary to create a object to be the parameter for SomeEvent? What would happen if I just passed inputObjects as the parameter to SomeEvent?
I am guessing that maybe the garbage collector would see no references to inputObjects, and would delete it when SomeMethod is finished.
It's not necessary to copy the list. The garbage collector will know that the object itself is still in use and it will not be garbage collected.
The difference between passing a copy and the original lies in the fact that if you pass the original, any modifications to the list will also be visible in the calling method whereas otherwise the modifications are only made to the copy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With