What is Ref and Out?
Ref and out are basically C# Keywords. These keywords are used for calling function by reference. These keywords passes the reference of the variable to the function instead of the value.
For example: Let's swap two integer variables values:
- public static void Swap(int a, int b)
- {
- int c = 0;
- c = a;
- a = b;
- b = c;
- Console.WriteLine("1) Values after swap a={0} b={1}",a,b);
- }
- static void Main(string[] args)
- {
- int a = 5;
- int b = 6;
- Swap(a,b);
- Console.WriteLine("2) Values after swap a={0} b={1}", a, b);
- Console.ReadKey();
-
- }
Here, we are swapping only the value but not swapping the value from actual address. If we want to swap value from memory location in C#, we need to use ref or out keyword.
For example
- public static void Swap(ref int a,ref int b)
- {
- int c = 0;
- c = a;
- a = b;
- b = c;
- Console.WriteLine("1) Values after swap a={0} b={1}",a,b);
- }
- static void Main(string[] args)
- {
- int a = 5;
- int b = 6;
- Swap(ref a,ref b);
- Console.WriteLine("2) Values after swap a={0} b={1}", a, b);
- Console.ReadKey();
- }
Here will be do actual swapping because we are passing address instead of value using ref keyword. We can do thr same as out keyword but there are some difference between ref and out keyword. Let's see about the difference between ref and out
Difference between Ref and out keyword
- Ref and out both used for passing parameter to a function.
- Ref keyword must be assigned a value before passing to the function whereas out keyword doesn't need to initialize before passing to the function.
What we can not do with ref and out keyword?
- Properties cannot be passed to ref or out parameters since internally they are functions not a member variable.
- Both Ref and Out cannot be used for method overloading simultaneously. Ref and Out treated differently at run time but actually they treated same at compile time.
For Example
- class MyClass
- {
- public void Method(out int a)
- {
-
- }
- public void Method(ref int a)
- {
-
- }
- }