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
The wording of the question is of the "Have you stopped hitting your wife?" variety—it assumes that out parameters are necessarily a bad idea. There are cases where out parameters can be abused, but…
They actually fit very well in the C# language. They are like ref parameters except that the method is guaranteed to assign a value to it and the caller doesn't need to initialize the variable.
Normal return values for functions are pushed onto the stack where they are called and exited. When you supply an out parameter, you're giving the method a specific memory address to stick the result in. This also allows for multiple return values, though using a struct often makes more sense.
They are wonderful for the TryParse Pattern and also provide metadata for other things like in the case of SQL-CLR where out parameters are mapped to out parameters of a stored procedure signature.
It's like the Tanqueray guy likes to say- Everything in moderation.
I definitely would stress against over-use, since it would lead to "writing c in c#" much the same way one can write java in Python (where you're not embracing the patterns and idioms which make the new language special, but instead simply thinking in your old language and converting to new syntax). Still, as always, if it helps your code be more elegant and make more sense, rock out.
They just ruin the semantics of a method/function a bit. A method should normally take a bunch of things, and spit out a thing. At least, that's how it is in the minds of most programmers (I would think).
I don't think they are. Misusing them is a bad idea, but that goes for any coding practice/technique.
The out keyword is necessary (see SortedDictionart.TryGetValue
). It implies pass by reference and also tells the compiler that the following:
int value;
some_function (out value);
is OK and that some_function
isn't using an unitialised value which would normally be an error.
the 'out
' is great!
It makes a clear statement that the parameter holds a value to be returned by the method.
The compiler also forces you to initialize it (if we are using as a return parameter, it should be initialized).