Both of the Ref and Out parameters are used to pass arguments to a method. Ref and Out both indicate that the parameter is being passed by reference. Let us see these two parameters one by one with sample code for each.
Ref parameter: the Ref parameter needs to be initialized before passing it to a method. The Ref keyword passes the parameter as a reference. In the case the parameter value is changed it is also reflected in the method. Check the following syntax for the Ref parameter.
Syntax
- // It is necessary to initialize the Ref parameter before passing to a method.
- int i = 10;
- //Ref Parameter passed to the method.
- Display(ref i);
As stated previously, when a variable is declared it needs to be initialized, so in the preceding syntax we have declared and initialized the variable before passing it to a method.
Sample Code
- class Program
- {
- static void Main(string[] args)
- {
- int i = 10;
-
- Display(ref i);
-
- Console.ReadLine();
- }
-
- public static void Display(ref int value)
- {
- Console.Write(value + 10);
- }
- }
Output
In the preceding example we have initialized the parameter to 10. And inside the Display method the ref parameter value is incremented with 10. If the ref parameter value is changed in the method that is being called then the parameter value is reflected in the calling method too.
Out Parameter: When passing a parameter to a method if there is no need to initialize the parameter then the Out parameter can be used. It is also passed as a reference. Since we do not initialize it before passing it to the method, it is necessary to initialize in the method in which it is being called before returning the value. Check the following syntax for the Out parameter.
Syntax
- // Variable is declared but there is no need to initialize.
- int a;
-
- Display(out a);
As we know there is no need to initialize the variable so we have just declared the variable. It will be initialized in the called method. Check the following code.
Sample Code
- class Program
- {
- static void Main(string[] args)
- {
- int a;
-
- Display(out a);
-
- Console.ReadLine();
-
- }
-
- public static void Display(out int x)
- {
- x = 10;
-
- Console.Write(x);
- }
-
- }
Output