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?
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 theMainStorage
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.