I read the C++ version of this question but didn\'t really understand it.
Can someone please explain clearly if it can be done and how?
There are several ways to do this. You can use ref
parameters:
int Foo(ref Bar bar) { }
This passes a reference to the function thereby allowing the function to modify the object in the calling code's stack. While this is not technically a "returned" value it is a way to have a function do something similar. In the code above the function would return an int
and (potentially) modify bar
.
Another similar approach is to use an out
parameter. An out
parameter is identical to a ref
parameter with an additional, compiler enforced rule. This rule is that if you pass an out
parameter into a function, that function is required to set its value prior to returning. Besides that rule, an out
parameter works just like a ref
parameter.
The final approach (and the best in most cases) is to create a type that encapsulates both values and allow the function to return that:
class FooBar
{
public int i { get; set; }
public Bar b { get; set; }
}
FooBar Foo(Bar bar) { }
This final approach is simpler and easier to read and understand.