Friday, August 31, 2007

C# ‘out’ Parameters: Good or Bad?

VB.NET supports two parameter passing modes: ByVal and ByRef. ByVal indicates changes made to the parameter by the method will not be reflected back to the caller. ByRef indicates changes made to the parameter by the method will be reflected back to the caller.

C# supports three parameter passing modes: ‘in’, ‘ref’, and ‘out’. ‘in’ is the same as the VB.NET ByVal. ‘ref’ is the same as the VB.NET ByRef. ‘out’ indicates the argument does not need to be initialized outside of the method, but this parameter must be set before the method returns.

I recently read two Microsoft articles on C# ‘out’ parameter passing. The first one, written by Peter Hallam, titled “Why does C# have both 'ref' and 'out'?”, explains why C# supports ‘out’ parameter passing and explains why it is a good thing. You can read this article at http://msdn2.microsoft.com/en-us/vcsharp/aa336814.aspx https://web.archive.org/web/20080408140708/http://msdn2.microsoft.com/en-us/vcsharp/aa336814.aspx. The second one, which is really an FxCop rule, titled “Avoid out parameters”, indicates that one should not use ‘out’ parameter passing. You can read this article at http://msdn2.microsoft.com/en-us/library/ms182131(VS.80).aspx.

After reading both articles and doing a little research on my own, I came to the conclusion that the ‘out’ parameter passing mode has its place. Part of this decision was based on the ‘out’ parameter’s usefulness in web service methods. I also decided that I is would be nice if VB.NET had an equivalent parameter passing mode.

The “Avoid out parameters” main argument against using ‘out’ parameters is as follows:
Although return values are commonplace and heavily used, the correct application of out and ref parameters requires intermediate design and coding skills. Library architects designing for a general audience should not expect users to master working with out or ref parameters.

I do not think this is a good reason for not using a language feature. I would like to hear other’s comments on the issue of whether or not using ‘out’ parameters in C# code is a good thing or a bad thing.

No comments: