C# Call By Reference

In C#, you can pass parameters to methods either by value or by reference. By default, parameters are passed by value, which means a copy of the parameter’s value is made and used within the method. However, you can use the ref and out keywords to indicate that a parameter should be passed by reference.

Here’s an example of how to use call by reference in C#:

using System;

class Program
    static void Main()
        int number = 10;
        Console.WriteLine("Before: " + number); // Output: Before: 10

        ChangeNumber(ref number);
        Console.WriteLine("After: " + number); // Output: After: 20

    static void ChangeNumber(ref int number)
        number = 20;

In the above example, we have a method called ChangeNumber that takes an int parameter number by reference using the ref keyword. Inside the method, we change the value of number to 20. In the Main method, we declare a variable number and pass it to the ChangeNumber method using the ref keyword. As a result, any changes made to the number parameter within the ChangeNumber method will affect the original variable in the Main method.

It’s worth noting that when using ref or out parameters, you must ensure that the variable being passed as a reference is assigned a value before passing it to the method.