Though both ref and out parameters are used to pass the parameters by reference, they aren’t used in exactly the same way.
Ref
Ref keywords are used to pass an argument as a reference, meaning that when the value of that parameter changes in the called method, the new value is reflected in the calling method. An argument passed using the ref keyword must be defined in the calling method before getting passed to the called method.
Out
Out keywords is similar to ref keywords but they are different because the arguments passed using out keywords can be passed without any value to be assigned to it. An argument passed using the out keyword must be defined in the called method before being returning to the calling method.
- public class Test {
- public static void Main()
- {
- int parameter1 = 1;
- int parameter2; // initialization optional.
- Function1(ref parameter1);
- Console.WriteLine(parameter1);
- -
- Function2(out parameter2);
- Console.WriteLine(parameter2);
- }
- static void Function1(ref int value)
- {
- value++; //here we get 0 in value so value++ we get 2.
- }
- static void Function2(out int value)
- we can not get parameter2 value here, we have to initialize value to variable before returning from this method.*/
- {
- value = 5;
- }
- }
-
- 2
-
-