Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are 'out' parameters in .NET a bad idea?

Tags:

.net

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. What other reasons are there?

like image 396
Kilhoffer Avatar asked Sep 25 '08 15:09

Kilhoffer


People also ask

Is it bad to use out parameter in C#?

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.

Why do we use out parameter in C#?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.

Do you need to declare an out variable before you use it in C#?

Variables passed as out arguments do not have to be initialized before being passed in a method call. However, the called method is required to assign a value before the method returns.

Should we initialize an out parameter before a method returns?

Generally speaking, out parameters must be initialized before the called method returns control to the caller.


2 Answers

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.

like image 192
Armin Ronacher Avatar answered Oct 19 '22 09:10

Armin Ronacher


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.

like image 26
Ben Hardy Avatar answered Oct 19 '22 09:10

Ben Hardy