Sometimes, when you share objects between parts of your program, changes in one place can unexpectedly affect others. This happens because they share the same reference, not a copy.
0
0
Common bugs from reference sharing in C Sharp (C#)
Introduction
When you pass an object to a method and want to understand why changes inside the method affect the original object.
When you assign one object variable to another and wonder why both seem to change together.
When debugging unexpected changes in data that seem to happen 'out of nowhere'.
When working with collections or classes and want to avoid accidental data modification.
When you want to create a copy of an object but accidentally just copied the reference.
Syntax
C Sharp (C#)
ClassName obj1 = new ClassName(); ClassName obj2 = obj1; // obj2 references the same object as obj1
Assigning one object variable to another copies the reference, not the actual object.
Both variables point to the same object in memory, so changes via one affect the other.
Examples
Both list1 and list2 point to the same list. Adding to list2 also changes list1.
C Sharp (C#)
List<int> list1 = new List<int> {1, 2, 3}; List<int> list2 = list1; list2.Add(4); Console.WriteLine(string.Join(",", list1));
Changing p2.Name also changes p1.Name because p1 and p2 reference the same Person object.
C Sharp (C#)
class Person { public string Name; } Person p1 = new Person { Name = "Alice" }; Person p2 = p1; p2.Name = "Bob"; Console.WriteLine(p1.Name);
Sample Program
This program shows that adding an item to fruits2 also adds it to fruits1 because both variables share the same list reference.
C Sharp (C#)
using System; using System.Collections.Generic; class Program { static void Main() { List<string> fruits1 = new List<string> { "Apple", "Banana" }; List<string> fruits2 = fruits1; // Both point to the same list fruits2.Add("Cherry"); Console.WriteLine("fruits1 contains:"); foreach (var fruit in fruits1) { Console.WriteLine(fruit); } } }
OutputSuccess
Important Notes
To avoid this bug, create a copy of the object instead of copying the reference.
For collections, use methods like List<T>.ToList() to clone.
For custom classes, implement a method to clone or copy the object.
Summary
Assigning one object variable to another copies the reference, not the object.
Changes through one reference affect all references to the same object.
To prevent bugs, create copies when you want independent objects.