Introduction
Ref and Out are two keywords in C# which give us an opportunity to pass a variable in methods by reference.
Both are treated differently at run-time but they are treated the same at compile time.
Add a Class and implement the following code:
- class Class3
- {
-
- static void Method1(int variable1)
- {
- variable1 = variable1 + 60;
- }
-
- public static void Main()
- {
- int variable2 = 40;
- Method1(variable2);
- Console.WriteLine(variable2);
- Console.ReadLine();
- }
- }
O/P - 40
Note
Whatever changes happened to variable1 in Method1() it is not going to reflect variable2. Hence, we could say that the data is passed by value.
Ref
Modify the class and use the ref keyword to pass by reference. In the below example, we can see that when we are working with variable1, we are actually working with variable2.
- class Class3
- {
-
- static void Method1(ref int variable1)
- {
- variable1 = variable1 + 60;
- }
-
- public static void Main()
- {
- int variable2 = 40;
- Method1(ref variable2);
- Console.WriteLine(variable2);
- Console.ReadLine();
- }
- }
O/P - 100
Note
Ref is always a Two way from Caller to Callee and Callee to Caller.
Out
It also passes by reference but we need to initialize variable1 within Method1() because even if we pass data from outside the function, it will still be discarded.
- class Class3
- {
-
- static void Method1(out int variable1)
- {
- variable1 = 30;
- variable1 = variable1 + 60;
- }
-
- public static void Main()
- {
- int variable2 = 40;
- Method1(out variable2);
- Console.WriteLine(variable2);
- Console.ReadLine();
- }
- }
O/P - 90
Note
Out is always one way that sends back data from Callee to Caller
So, when do we use what?
If we have to return more than one value from a method, we would go for the out keyword.The below example demonstrates the exact usage where we are actually getting two results using the out keyword. Check out the Add_Sub() method below.
Code
-
- static void Add_Sub(int x, int y, out int add_result, out int sub_result)
- {
- add_result = x + y;
- sub_result = x - y;
- }
-
- public static void Main()
- {
- int result_add ;
- int result_sub;
- Add_Sub(20,20,out result_add,out result_sub);
- Console.WriteLine("Add : " + result_add);
- Console.WriteLine("Sub : " + result_sub);
- Console.ReadLine();
- }
As a suggestion, beginners should make use of the breakpoints to debug and understand the concept...
Happy Learning...