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
- UInt32.Parse(String) Method in C# with Examples
- Int32.Parse(String) Method in C# with Examples
- UInt16.Parse(String) Method in C# with Examples
- Int16.Parse(String) Method in C# with Examples
- UInt64.Parse(String) Method in C# with Examples
- Int64.Parse(String) Method in C# with Examples
- How to Install and Setup Visual Studio for ASP.NET?
- Object.MemberwiseClone Method in C# with Examples
- C# | ArrayList.InsertRange() Method
- LINQ | Aggregate Operators | LongCount
- LINQ | How to find aggregate of the given sequence?
- Check if ValueTuple instances are equal in C#
- LINQ | Join (Inner Join)
- C# | ValueTuple <T1,T2,T3,T4> Struct
- C# | ValueTuple <T1> Struct
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.