Structs are copied on assignment C# with Example



Structs are copied on assignment C# with Example

Sinse structs are value types all the data is copied on assignment, and any modification to the new copy does not 
change the data for the original copy. The code snippet below shows that p1 is copied to p2 and changes made on 
p1 does not affect p2 instance. 
var p1 = new Point { 
x = 1, 
y = 2 
}; 
Console.WriteLine($"{p1.x} {p1.y}"); //  1  2 
var p2 = p1; 
Console.WriteLine($"{p2.x} {p2.y}"); // Same output: 1 2 
p1.x = 3; 
Console.WriteLine($"{p1.x} {p1.y}"); //  3  2 
Console.WriteLine($"{p2.x} {p2.y}"); // p2 remain the same: 1 2 

0 Comment's

Comment Form

Submit Comment