In C# values of basic data type such as int, float, char, etc … are send as pass-by-value and values of user define data types or object values are send by as pass-by-reference.
However c# give the flexibility to send values of you basic data type as pass-by-reference too, for that ref key work is use .there is some situation when we did not pass a value to function but we want to get value for the function such as pass a number to the function and want to get its remainder and dividend from the function to handle this situation c# has a key word out that is use to pass value from a function to the caller function.
Ref parameter in c#
Use to send basic data type by pass-by-reference .ref variable can’t be used for initialization purpose.
Ref variable is define in function definition and function call. Ref variable must me assign a value before the first call because the compiler will consider as valid reference and pass it to the calling function if we did not assign it value the parameter in the function will get a reference pointing to nothing thus this a programming error.(example1)
Ref variable is also used to send object to a function as reference-by-reference. In c# object reference usually send reference-by-value mean the reference of a variable is copied to other variable they are pointing to same object but have their on copy of reference. The parameter variable cannot change the original variable reference.
Sending reference-by-reference is method that both the real variable and the parameter variable as the same copy of reference, the parameter variable in the calling function can change the object pointed by the original variable or by variable in the caller function.(example2)
Out parameter in c#
Out parameter can only be used to pass a parameter value out of the function.
Out can used without initialization but it must be assign a value before returning from the function for which the out parameter is used. this parameter can be used for initialization purpose.(example3)
Ref and Out Parameter in C#
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Ibrahim RashidPosted Jul 16, 2014, 4:58 AM
Nice article, Thanks Simi. I want to just add one important notes about out and ref keyword. Boths are used as reference type.Because when it's value assigned or changed in called method,it reflects changes in calling method.
johnson yuanPosted Jul 6, 2014, 1:27 PM
I found a wrong word in Ref parameter in c# section, 2nd para, you said 'first call because he compiler ', I beliebe the 'he' should be 'the'.