Why are \'out\' parameters in .NET a bad idea?
I was recently asked this, but I had no real answer besides it\'s simply unnecessarily complicating an application. Wh
I'd say that your answer is spot on; it's generally unnecessary complication and there's usually a simpler design. The majority of the methods you work with in .NET don't mutate their input parameters, so having a one-off method that utilizes the syntax is a bit confusing. The code becomes a bit less intuitive, and in the case of a poorly documented method, we have no way of knowing what the method does to the input parameter.
Additionally, method signatures with out parameters will trigger a Code Analysis/FxCop violation, if that's a metric you care about. In most cases, there's a better way to accomplish the intent of a method that uses an "out" parameter and the method can be refactored to return the interesting information.
I think in some scenarios they are a good idea because they allow more than 1 object to be returned from a function for example:
DateTime NewDate = new DateTime();
if (DateTime.TryParse(UserInput, out NewDate) == false) {
NewDate = DateTime.Now;
}
Very useful :)
If you care about writing reliable code by embracing immutability and removing side effects, then out parameters are an absolutely terrible idea. It forces you to create mutable variables just to deal with them. (Not that C# supports readonly method-level variables anyway (at least in the version I'm using, 3.5)).
Secondly, they reduce the compositionality of functions by forcing the developer to set up and deal with the variables which receive the out values. This is annoying ceremony. You can't just go and compose expressions using them with anything resembling ease. Therefore code calling these functions quickly turns into a big imperative mess, providing lots of places for bugs to hide.
The out variable is not bad anyway, its really a cool stuff to use out if we need to return multiple (2 specifically) variables from a function. Sometimes its really tedious work to create a custom object just for the purpose of returning 2 variables, out is the ultimate solution.