Does this copy the reference or the object?

Posted by Water Cooler v2 on Stack Overflow See other posts from Stack Overflow or by Water Cooler v2
Published on 2010-06-16T16:46:27Z Indexed on 2010/06/16 16:52 UTC
Read the original article Hit count: 199

Sorry, I am being both thick and lazy, but mostly lazy. Actually, not even that. I am trying to save time so I can do more in less time as there's a lot to be done.

Does this copy the reference or the actual object data?

public class Foo
{
    private NameValueCollection _nvc = null;

    public Foo( NameValueCollection nvc)
    {
        _nvc = nvc;
    }
}

public class Bar
{
    public static void Main()
    {
        NameValueCollection toPass = new NameValueCollection();
        new Foo( toPass ); // I believe this only copies the reference
                           // so if I ever wanted to compare toPass and 
                           // Foo._nvc (assuming I got hold of the private 
                           // field using reflection), I would only have to
                           // compare the references and wouldn't have to compare
                           // each string (deep copy compare), right?
}

I think I know the answer for sure: it only copies the reference. But I am not even sure why I am asking this.

I guess my only concern is, if, after instantiating Foo by calling its parameterized ctor with toPass, if I needed to make sure that the NVC I passed as toPass and the NVC private field _nvc had the exact same content, I would just need to compare their references, right?

© Stack Overflow or respective owner

Related posts about c#

Related posts about object-oriented-design