Difference between Ref and Out parameters S.
No 1 Ref Out
Ref parameters are both input and Out parameters are only for output - a output - a value is passed into a value is passed out of a method method and a new value is passed out An argument passed to parameter must be initialized ref out argument does not have to be explicitly initialized.
2 3 4
Ref parameter may be written to Out parameter must be written to before returning from method before returning from method Ref parameter may be referenced Out parameter may not be referenced inside method before being inside method before being written to written to
Example for ref parameter : class Program { static void M1(ref int i) { i = 1; i += 1; } static void Main(string[] args) { int j=0; //Assigned M1(ref j); [Link](j); [Link](); } } The output is same: 2, but we have to assign the variable before used otherwise we will get an error. Example for out parameter : class Program { static void M1(out int i) { i = 1; i += 1; } static void Main(string[] args) {
int j; //Not assigned M1(out j); [Link](j); [Link](); } } } The output is : 2 Summary: 1. Both are treated differently @ runtime but same in the compile time, so cant be overloaded. 2. Both are passed by references except ref requires that the variable to be initialized before passed. And, further updates on difference between questions and answers, please visit my blog @ [Link]