What is the difference between ref
and out
parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?
ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.
out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way. out keyword is used to get data in uni-directional way. Before passing a variable as ref, it is required to be initialized otherwise compiler will throw error.
Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference. By default parameters are passed to a method by value. By using these keywords (ref and out) we can pass a parameter by reference.
When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.
They're pretty much the same - the only difference is that a variable you pass as an out
parameter doesn't need to be initialized but passing it as a ref
parameter it has to be set to something.
int x; Foo(out x); // OK int y; Foo(ref y); // Error: y should be initialized before calling the method
Ref
parameters are for data that might be modified, out
parameters are for data that's an additional output for the function (eg int.TryParse
) that are already using the return value for something.
Why does C# have both 'ref' and 'out'?
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.
So, out
means out, while ref
is for in and out.
These correspond closely to the [out]
and [in,out]
parameters of COM interfaces, the advantages of out
parameters being that callers need not pass a pre-allocated object in cases where it is not needed by the method being called - this avoids both the cost of allocation, and any cost that might be associated with marshaling (more likely with COM, but not uncommon in .NET).
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