C
C#3y ago
Pacrombie

❔ C# Fundamental: does setting one object to another point or copy?

public SomeType someObject = new SomeType();
public SomeType anotherObject = someObject;
public SomeType someObject = new SomeType();
public SomeType anotherObject = someObject;
this is probably a braindead question but in this code, is anotherObject "pointing" to someObject (changing the instance variables of one will change the other's) or does anotherObject copy the values of someObject into a new object? im new to the language and trying to develop an understanding
9 Replies
mtreit
mtreit3y ago
Yes it's pointing to it
ero
ero3y ago
this doesn't compile but it would point, yes
Pacrombie
PacrombieOP3y ago
i know it doesn't compile, i was just trying to get the point across thank you
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX3y ago
tebeco#0205
REPL Result: Success
int i = 3;
int j = i;
Console.WriteLine((i, j));
j = 5;
Console.WriteLine((i, j));
i = 1;
Console.WriteLine((i, j));
int i = 3;
int j = i;
Console.WriteLine((i, j));
j = 5;
Console.WriteLine((i, j));
i = 1;
Console.WriteLine((i, j));
Console Output
(3, 3)
(3, 5)
(1, 5)
(3, 3)
(3, 5)
(1, 5)
Compile: 602.492ms | Execution: 76.052ms | React with ❌ to remove this embed.
MODiX
MODiX3y ago
mtreit#6470
REPL Result: Success
SomeType someObject = new SomeType();
SomeType anotherObject = someObject;
Console.WriteLine(object.ReferenceEquals(someObject, anotherObject));

class SomeType
{
}
SomeType someObject = new SomeType();
SomeType anotherObject = someObject;
Console.WriteLine(object.ReferenceEquals(someObject, anotherObject));

class SomeType
{
}
Console Output
True
True
Compile: 649.891ms | Execution: 74.328ms | React with ❌ to remove this embed.
mtreit
mtreit3y ago
You can use ReferenceEquals if you want to see if two variables point to the same object on the heap
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?