In C# by default the parameters are always passed by value but you can also use out and ref keywords for passing parameters by reference.
Both keywords are identical with the only difference of initializing the value of the variable. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn’t differentiates between the two while it created IL for ref and out).
Sample Code
using System; namespace HelloWorld { class Hello { static void Main() { Console.WriteLine("**********Using Ref Method**********"); int num = 10; MyMethodRef(ref num); Console.WriteLine("Value Outer Method : {0}", num); Console.WriteLine("**********Using Out Method**********"); int numout = 10; MyMethodOut(out num); Console.WriteLine("Value Outer Method : {0}", numout); } private static void MyMethodRef(ref int number){ number += 20; Console.WriteLine("Value Inner Method : {0}", number); } private static void MyMethodOut(out int number) { number = 20; Console.WriteLine("Value Inner Method : {0}", number); } } } Output **********Using Ref Method********** Value Inner Method : 30 Value Outer Method : 30 **********Using Out Method********** Value Inner Method : 20 Value Outer Method : 10
Using Ref
With Ref keyword, the objects is initialized first before used in the function, you need to set the value first then call in the method to read and modify. If you tried to pass num variable without initializing to the MyMethodRef() method, you’d end up with a compilation error: Use of unassigned variable ‘num‘.
Using Out
With Out keyword, the variable have to be assigned inside the function. A variable passed in using out cannot be read from before its assigned to.
The method must be set it before returning.
You can use out and ref parameters for overloading methods. static void Method(String name){} static void Method(ref String name){} //ok static void Method(out String name){} //error
You can overload the standard method by using the ref or out keywords but cannot overload that differs only by out and ref simultaneously. The parameter’s type must match the type of the value that is passed.