Reference assignment lets two variables point to the same object. This means changes through one variable affect the other because they share the same data.
0
0
Reference assignment and shared state in C Sharp (C#)
Introduction
When you want multiple variables to work with the same object without copying it.
When you want to save memory by not duplicating large objects.
When you want changes in one place to be seen everywhere the object is used.
Syntax
C Sharp (C#)
ClassName variable1 = new ClassName();
ClassName variable2 = variable1;Both variable1 and variable2 now point to the same object.
Changing the object via one variable changes it for the other too.
Examples
Both
box1 and box2 point to the same Box object. Changing box2.Size also changes box1.Size.C Sharp (C#)
class Box { public int Size; } Box box1 = new Box(); box1.Size = 5; Box box2 = box1; box2.Size = 10;
Strings are reference types but immutable, so even if
s2 points to the same string, you cannot change the string content.C Sharp (C#)
string s1 = "hello";
string s2 = s1;Sample Program
This program shows that changing the Size property through box2 also changes it for box1 because both variables refer to the same object.
C Sharp (C#)
using System; class Box { public int Size; } class Program { static void Main() { Box box1 = new Box(); box1.Size = 5; Box box2 = box1; // box2 points to the same object as box1 box2.Size = 10; // change Size via box2 Console.WriteLine($"box1.Size = {box1.Size}"); Console.WriteLine($"box2.Size = {box2.Size}"); } }
OutputSuccess
Important Notes
Reference types include classes, arrays, and delegates.
Value types like int or struct copy the data, so changes do not affect the original.
Be careful: unintended shared state can cause bugs if you change an object without realizing others use it too.
Summary
Reference assignment makes two variables point to the same object.
Changes through one variable affect the other because they share the same data.
Use reference assignment to save memory and share data, but watch out for unexpected changes.