ref in C#
The ref keyword in C# is used for passing or returning references of values to or from Methods. Basically, it means that any change made to a value that is passed by reference will reflect this change since you are modifying the value at the address and not just the value. It can be implemented in the following cases:
- To pass an argument to a method by its reference.
- To define a method signature to return a reference of the variable.
- To declare a struct as a ref struct
- As local reference
Example 1: Here, we define two methods addValue and subtractValue. The method addValue is a method that only modifies the value of its parameter. Therefore when the value of ‘a’ is displayed after passing it as a parameter to addValue there is no difference in its value. Whereas the method subtractValue uses the reference of the parameter, the keyword ref indicating the same. Hence when the value of ‘b’ is displayed after passing it as a parameter to subtractValue, you can see the changes are reflected in its value. The ref keyword must be used in the method definition as well as when the method is called.
Initial value of a is 10 Initial value of b is 12 Value of a after addition operation is 10 Value of b after subtraction operation is 7
Example 2: You may use the keyword ref with an instance of a class as well. In the program given below, we have a class Complex to represent Complex numbers. The class also consists of an update method that uses the object’s reference and reflects the updates made in the value of the real and imaginary part of the object.
Complex number C = 2 + i 4 After updating C Complex number C = 7 + i 9