views:

2600

answers:

18

I was recently asked this, but had no real answer besides it simply unnecessarily complicating an application. What other reasons are there?

A: 

I would say the answer you gave is about the best there is. You should always design away from out parameters if possible, because it usually makes the code needlessly complex.

But this is true of just about any pattern. If there is no need for it, don't use it.

Geoffrey Chetwood
I think a blanket statement asserting that 'it usually makes the code needlessly complex' is a pretty gross generalization. There are lots of contexts in which using an out parameter would simplify your design, not complicate it. That's why it's in the language in the first place.
Ben Collins
@Ben Collins: I know, that is why I said "usually", "if possible", etc.
Geoffrey Chetwood
A: 

I don't think there is a real reason although I haven't seen it used that often (other then p-invoke calls).

Dror Helper
+29  A: 

Well, they aren't a bad idea I think. Dictionary<K, V> has a TryGetValue method which is a very good example why out parameters are sometimes a very nice thing to have.

You should not overuse this feature of course, but it's not a bad idea per definition. Especially not in C# where you have to write down the out keyword in function declaration and call which makes it obvious what's going on.

Armin Ronacher
A: 

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.

Skizz

Skizz
+11  A: 

They are a good idea. Because sometimes you just want to return multiple variables from one method, and you don't want to create a "heavy" class structure for this. The wrapping class structure can hide the way the information flows.

I use this to:

  • Return key and IV data in one call
  • Split a person name, into different entities (first-, middle-, lastname)
  • Split the address
GvS
If you don't want a "heavy" class structure, what's wrong with using a struct in C# instead of a full-blown class?
dsimcha
Because it will add complexity to your code. Instead of a simple call, you have added a dependency to an extra type.
GvS
+3  A: 

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.

Gabriel Isenberg
+1  A: 

I don't think they are. Misusing them is a bad idea, but that goes for any coding practice/technique.

Kevin
A: 

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 :)

GateKiller
It is irrelevant to initialize the variable as it because of the out keyword always will be treated as an unassigned parameter to the method (until set).I would also avoid using the equals false syntax and just negate the expression itself.
troethom
I could never understand rationale behind this "if (b == false)" stuff. Shouldn't you expand this into even more explicit "if ((b == false) == true)"? :)
Constantin
@Constantin, what I find more gross is seeing something like this:if (x == true) return true;else return false;
Dana
+2  A: 

I's not alwyas a bad idea to use out parameters. Usualy for the code that tries to create an object based on some form of input it's a good idea to provide a Try method with out parameters and boolean return value, not to force the method consumer to wrap try catch blocks all over, not to mention the better performance. Example:

bool TryGetSomeValue(out SomeValue value, [...]);

this is a case where out parameters are a good ideea.

Another case is where you want to avoid costly large structure passing between methods. For example:

void CreateNullProjectionMatrix(out Matrix matrix);

this version avoids costly struct copying.

But, unless out is needed for a specific reason, it should be avoided.

Pop Catalin
Your second example could be rewritten as matrix.CreateNullProjectionMatrix (), i.e. a member function. Or use a constructor parameter to specify the initial matrix state. Or use derived types to initialise based on type (i.e. ProjectionMatrix : Matrix).
Skizz
The point of the second example is that it avoids struct copying. If it were to return the Matrix as a function return value, the Matrix would have been pushed in the stack prior to function exit the poped out after function return, in my example this doesn't happen
Pop Catalin
Performance cannot be an argument. Refactoring the code so the struct is not copied upon return is something the compiler should (and can, often trivially) do. Pushing this task to the programmer is wrong and no argument for `out` at all.
Konrad Rudolph
Konrad, check out XNA Class library, out is used extensively for performance reasons. http://msdn.microsoft.com/en-us/library/bb195649.aspx for example. Feel free to browse for more.
Pop Catalin
A: 

I would have to agree with GateKiller. I can't imagine out parameters being too bad if Microsoft used them as part of the base library. But, as with all things, best in moderation.

Jason Z
+1  A: 

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.

callingshotgun
A: 

Some languages outside of .Net use them as do nothing macros that simply give the programmer information about how the parameters are being used in the function.

Slapout
A: 

One point I don't see mentioned is that the out keyword also requires the caller to specify out. This is important since it helps to make sure that the caller understands that calling this function will modify his variables.

This is one reason why I never liked using references as out parameters in C++. The caller can easily call a method without knowing his parameter will be modified.

Torlack
+1  A: 

Out - Parameter are a bad idea in my opinion. They increase the risk of side effects and are hard to debug. The only good solution are function results and here is the problem: For function results, you have to create for every complex result a tuple or a new type. Now it should be fairly easy in c#, with anonymous types and generics.

And by the way: I hate side effects too.

ChaosSpeeder
A: 

Well , there is no clear answer for this,but simple use case for out parameter would be "Int.TryParse("1",out myInt)"

The XXX.TrayParse method job is, it converts a value of some type, to another type, it returns to you a boolean flag to indicate the conversion success or failure, which is one part the other part is the converted value, which is carried by the out parameter in that method.

This TryParse method was introduced in .NET 2.0 to get over the fact that XXX.Parse will through an exception if conversion fails and you have to put in try/catch around the statement.

So basically it depends on what your method is doing, and what method callers are expecting, if you are doing a method that returns some form of response codes , then out parameters could be use to carry out method returned results.

anyway Microsoft says "Avoid using out parameters" , in their design guideline , check this msdn page http://msdn.microsoft.com/en-us/library/ms182131(VS.80).aspx

Mohamed Faramawi
A: 

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).

Jonas
+1  A: 
Mufasa
A: 

The wording of the question is of the Have you stopped hitting your wife? variety--it asumes that they're necessarily a bad idea.

There are cases where out parameters can be abused but they actually fit very well in the C# language. They're like ref parameters except 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're 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.

Mark Cidade