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 subtration 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
- C# Program to Convert a Binary String to an Integer
- Basics of FileStream in C#
- C# Program for Nested Conditional Operator
- C# Program for Converting Hexadecimal String to Integer
- Program to Input Weekday Number and Print the Weekday in C#
- What is NuGet?
- Top 10 Programming Languages for Blockchain Development
- C# Program to Convert the Octal String to an Integer Number
- int Keyword in C#
- ulong keyword in C#
- long keyword in C#
- ushort keyword in C#
- short keyword in C#
- decimal keyword in C#
- double Keyword in C#
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.