Search code examples
c#.netreferencevalue-typereference-type

How to determine if a value is copied or referenced?


Let's say we have a program that works like this:

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Storage MainStorage = new Storage();

            PrintData Printer = new PrintData();

            Printer.GetStorage(MainStorage);
        }
    }

    class Storage
    {
        //Stores some data
    }

    class PrintData
    {
        Storage storage;

        public void GetStorage(Storage storage)
        {
            this.storage = storage;
        }

        public void Print()
        {
            //Prints data
        }
    }
}

It's just an example so the code wont be perfect but my question is in this instance does the GetStorage() method make a copy of the MainStorage object or does it make a reference to it?


Solution

  • Its just an example so the code wont be perfect but my question is in this instance does the GetStorage() method make a copy of the MainStorage object or does it make a reference to it?

    It makes a copy of the reference to the Storage instance. In this case, the field in PrintData will reference the same instance in memory as the one you assign to MainStorage.

    You can check to see whether assignment has reference semantics by checking whether the type is a class or a struct. If it's a value type (struct), then the copy will have value copying semantics.