dimitris93
dimitris93

Reputation: 4273

C# objects and memory managment

Lets say i have the following code where Car class has only 1 property : String modelname

Car c = new Car("toyota");
Car c1 = c;
Car c2 = c;
Car c3 = c;
Car c4 = c;
Car c5 = c;

Is this going to make a new copy of car c every time ? So there will be a new "toyota" String 5 times more in the memory ? Or the "toyota" string will be in the memory only once ?

Edit: Adding this relevant link in case you had the same question as i did, i think it helps Are arrays or lists passed by default by reference in c#?

Upvotes: 1

Views: 191

Answers (3)

Selman Genç
Selman Genç

Reputation: 101680

Assigning a reference type is only copies the reference (in other words address) of the object into the variable. It doesn't copy the actual data since the reference type variables only hold reference values or in other words an address that indicates where the actual data lives in memory. So in this case you will have 6 reference type variable that hold a reference to the same address in the memory.

Upvotes: 2

mservidio
mservidio

Reputation: 13057

Car is a Reference type, so the answer is no. See: What is the difference between a reference type and value type in c#?.

Upvotes: 3

adv12
adv12

Reputation: 8551

No, the "toyota" string will be in memory only once, because there will only be one Car object, with 6 references pointing to it.

Upvotes: 6

Related Questions