I am trying to refresh my understanding of C#. I have used Java before and passing by reference is a powerful tool that I truly miss in Java. However, I needed clarification if there is even a need to pass an object by reference and if there is a scenario where it may be helpful? Stackoverflow already has multiple questions around reference and they were truly enlightening, however, I was wondering if there is a scenario for passing objects by reference. Let me attach the code to better illustrate it.
class Program
{
public static void Update(int x) { x++; }
public static void Update(ref int x) { x++; }
public static void Update(Employee x) { x.msalary += 2000; }
public static void Update(ref Employee x) { x.msalary += 2000; } //Do we even need this method? Is there a scenario where we might need this?
static void Main(string[] args)
{
int a = 0;
Update(a);
Console.WriteLine("T1 " + a.ToString()); //a is still 0
Update(ref a);
Console.WriteLine("T2 " + a.ToString());//a is 1
Employee emp2 = new Employee("Brent", "1234", "Blue", 1000); //salary is 1000
Update(emp2.msalary);
Console.WriteLine("T3 " + emp2.msalary.ToString());//salary does not change.
Update(ref emp2.msalary);
Console.WriteLine("T4 "+emp2.msalary.ToString());//salary changes to 1001
Update(emp2);
Console.WriteLine("T5 " + emp2.msalary.ToString()); //This changes, as expected for objects.
Update(ref emp2);
Console.WriteLine("T6 " + emp2.msalary.ToString()); //This also changes. But is there a scenario where we might need this?
}
}