ref Keyword Vs out Keyword
The
ref
modifier means that:- The value is already set and
- The method can read and modify it.
The
out
modifier means that:- The Value isn't set and can't be read by the method until it is set.
- The method must set it before returning.
Ref
The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.
Out
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.
Program with ref and out keyword
- public class Example
- {
- public static void Main() //calling method
- {
- int val1 = 0; //must be initialized
- int val2; //optional
- Example1(ref val1);
- Console.WriteLine(val1); // val1=1
- Example2(out val2);
- Console.WriteLine(val2); // val2=2
- }
- static void Example1(ref int value) //called method
- {
- value = 1;
- }
- static void Example2(out int value) //called method
- {
- value = 2; //must be initialized
- }
- }
- /* Output
- 1
- 2
- */
Note
- Do not be confused with the concept of passing by reference and the concept of reference type. These two concepts are not the same.
- A value type or a reference type can be passed to method parameter by using ref keyword. There is no boxing of a value type when it is passed by reference.
- Properties cannot be passed to ref or out parameters since internally they are functions and not members/variables.
No comments:
Post a Comment