what is the difference between ref keyword and out keyword in C#?
1)Ref and out keywords used to return multiple values. 2)if you pass a variable as ref ,you must initialize that variable before pass to the method. 3)initialization is not must in out but initialize that variable before return the method
The ref keyword causes arguments to be passed by reference. The effect is that any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keywordAn argument passed to a ref parameter must first be initialized. This differs from out, whose argument need not be explicitly initialized before being passedAlthough ref and out are treated differently at run-time, they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument.These two methods, for example, are identical in terms of compilation, so this code will not compile:class CS0663_Example { // compiler error CS0663: "cannot define overloaded // methods that differ only on ref and out" public void SampleMethod(ref int i) { } public void SampleMethod(out int i) { }}Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:class RefOutOverloadExample{ public void SampleMethod(int i) { } public void SampleMethod(ref int i) { }}
Refer this url:http://www.c-sharpcorner.com/Language/out_and_ref.asp
Difference is that out parameters need to be declared but not initialized.Ref parameter will have a value even before the method call..Anyhow, any change to this argument in the called method will affect the value of the actual variable.