Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code correct to create a new object for the parameter to an event?

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.

like image 386
user1725145 Avatar asked Nov 30 '25 15:11

user1725145


1 Answers

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

like image 96
Kenneth Avatar answered Dec 02 '25 03:12

Kenneth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!