The Ref and Out parameter is used when your method wants to return one or more values.
Ref Keyword:
While using the Ref keyword we need to initialize the parameter before passing to metod. If you want to pass variable as Ref parameter you need to initialize before pass. Ref keyword will pass parameter as reference, it means when the value of parameter is changed in called method it get reflected in calling method.
Example:
- class Program
- {
- static void Main(string[] args)
- {
- int intRef = 2;
- int Value = MethodCall(ref intRef);
- Console.WriteLine("Ref Value : " + Value);
- Console.ReadLine();
- }
-
- private static int MethodCall(ref int intRef)
- {
- return 5 + intRef;
- }
-
- }
Output: Ref Value : 7
Out Keyword:
While using Out keyword we don’t need to initialize the parameter before passing to method. Out keyword also you pass as parameter as reference but here we need to initialize out parameter before it return to calling method.
Example:
- static void Main(string[] args)
- {
- int intOut;
- int Value = MethodCall(out intOut);
- Console.WriteLine("Out Value : " + Value);
- Console.ReadLine();
- }
-
- private static int MethodCall(out int intOut)
- {
- return intOut = 3;
- }
Output: Out Value : 3
Note:
- Passing by reference and the concept of reference type these two concepts are not the same.
- Properties cannot be passed to ref or out parameters since internally they are functions.