Passing reference types to methods lets you change the original object inside the method. This helps when you want to update or modify data without making a copy.
0
0
Passing reference types to methods in C Sharp (C#)
Introduction
When you want a method to update the contents of an object you pass in.
When you want to avoid copying large objects for better performance.
When you want multiple methods to work on the same object and see changes.
When you want to share data between different parts of your program easily.
Syntax
C Sharp (C#)
void MethodName(ClassName obj) { // use or modify obj }
The method receives a reference to the original object, not a copy.
Changes to the object's properties inside the method affect the original object.
Examples
This method changes the Name property of the Person object passed in.
C Sharp (C#)
class Person { public string Name; } void ChangeName(Person p) { p.Name = "Alice"; }
This method clears all items from the original list passed in.
C Sharp (C#)
void ResetList(List<int> numbers) { numbers.Clear(); }
Sample Program
This program shows how passing a reference type (Person) to a method lets us change its Name property. It also shows clearing a list affects the original list.
C Sharp (C#)
using System; using System.Collections.Generic; class Person { public string Name; } class Program { static void ChangeName(Person p) { p.Name = "Alice"; } static void Main() { Person person = new Person(); person.Name = "Bob"; Console.WriteLine("Before: " + person.Name); ChangeName(person); Console.WriteLine("After: " + person.Name); List<int> numbers = new List<int> {1, 2, 3}; Console.WriteLine("List count before: " + numbers.Count); numbers.Clear(); Console.WriteLine("List count after: " + numbers.Count); } }
OutputSuccess
Important Notes
If you assign a new object to the parameter inside the method, it won't change the original reference outside.
To replace the original object itself, you can use the ref keyword.
Summary
Passing reference types means methods get access to the original object.
Modifying the object's properties inside the method changes the original.
Assigning a new object inside the method does not affect the original reference unless ref is used.