What is the difference between
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?
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.
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.
out means out, while
ref is for in and out.
These correspond closely to the
[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).