I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:
public void myFunction(ref MyClass someClass)
and
public void myFunction(out MyClass someClass)
Which should I use and why?
The ref and out keywords both use the concept of Pass by Reference with data, but with some compiler restrictions. You can think ref keyword as two way where data passed from caller to callee and back while out keyword is a one way, it sends data from calle to caller and any data passed by a caller is discarded.
Explanation: Variable 'i' is passed as reference parameter declared with 'ref' modifier and variable 'j' is passed as a output parameter declared with 'out' keyword. Reference parameter used to pass value by reference is the same with out parameter.
You can use the out keyword in two contexts: As a parameter modifier, which lets you pass an argument to a method by reference rather than by value. In generic type parameter declarations for interfaces and delegates, which specifies that a type parameter is covariant.
The ref keyword indicates that a value is passed by reference. It is used in four different contexts: In a method signature and in a method call, to pass an argument to a method by reference. For more information, see Passing an argument by reference. In a method signature, to return a value to the caller by reference.
ref
tells the compiler that the object is initialized before entering the function, while out
tells the compiler that the object will be initialized inside the function.
So while ref
is two-ways, out
is out-only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With