Reputation: 47
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?
Upvotes: 3
Views: 738
Reputation: 564791
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.
Upvotes: 4
Reputation: 36614
In this example, it gets a copy of the reference, not the object itself.
Classes are always copied by reference. Structs and enums are copied by value unless you use the keyword ref
in the method parameter.
String is a special case of class, being immutable (cannot be changed), whenever you modify it the reference points to a new object representing the result, so, it's a copy of the value effectively.
Upvotes: 1