C
C#2y 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
mtreit2y ago
Yes it's pointing to it
ero
ero2y ago
this doesn't compile but it would point, yes
Pacrombie
PacrombieOP2y ago
i know it doesn't compile, i was just trying to get the point across thank you
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2y 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
MODiX2y 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
mtreit2y ago
You can use ReferenceEquals if you want to see if two variables point to the same object on the heap
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y 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.
Want results from more Discord servers?
Add your server