1

From what I understood from Made one instance of a class equal to another. – How to cancel that?, objects are simply references to memory meaning that if two objects are equal to each other and one change is made to one object, the same change should apply to another object.

However, when I run this code:

Point original = new Point(100, 100);
Point temp = original;
original.X += 100;
Console.WriteLine(original);
Console.WriteLine(temp);

The output of original and temp is different. Am I missing something?

Here is the output:

{X=200,Y=100}
{X=100,Y=100}
Community
  • 1
  • 1

4 Answers4

6

Assuming that Point is the Point structure, it is a value type. struct's are value types.

Value types are copied by value in their entirety. so each is a new copy. This is different to Reference Types, where only the Reference (the thing that points at the memory) is copied.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
2

From Point Structure you will notice that the Point is a struc and from struct (C# Reference)

A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.

Also from Structs (C# Programming Guide)

Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
0

What Made one instance of a class equal to another. – How to cancel that? discusses is true for Reference types.

Here you have a Value type.

Community
  • 1
  • 1
0

Please see the diagram , demonstration value type demo

pravprab
  • 2,301
  • 3
  • 26
  • 43