In many cases you may need to be able to call a function and return multiple values. Many times this functionality is implemented by utilizing an array or similar object as the return value and simply reading the contents back into variables. The following example demonstrates a different approach that utilizes an out parameter. Briefly defined an out parameter can be used to return the values in the same variable passed as a parameter of the method. Coincidentally any changes made to the parameter will be reflected in the variable. The concept of out parameters is further explained in my posting titled "Out vs. Ref Parameters in C#".
| public void foo(out int bar) |
| { |
| bar = 1; |
| } |
| |
| private void foobar() |
| { |
| int baz; |
| foo(out baz); |
| Console.WriteLine(baz); |
| } |
OR
| public void foo(out int bar) |
| { |
| try |
| { |
| bar = 1; |
| } |
| catch |
| { |
| throw; |
| } |
| } |
| |
| private void foobar() |
| { |
| int baz; |
| foo(out baz); |
| Console.WriteLine(baz); |
| } |