user496949
user496949

Reputation: 86085

what is the pros and cons of using out parameter

Anyone can point out the pros and cons of the out parameter. When it is preferred to use out parameter rather than just to return a value.

Upvotes: 4

Views: 2472

Answers (3)

asdfjklqwer
asdfjklqwer

Reputation: 3594

Out parameters effectively allow you to return multiple values from a method, and this is generally preferable to returning an arbitrary struct or tuple which contains multiple values.

One might argue that it's easier to overlook the possible side effects of a function which uses an out parameter, as it departs from the traditional 'multiple parameters, one return value' model. But I honestly think that the out keyword coupled with a method post-condition makes the programmer's intention quite clear.

Upvotes: 7

Ken Henderson
Ken Henderson

Reputation: 2828

I would suggest taking a look at the TryParse methods on the built in types like int. The return value is a bool to indicate success while the value is returned via an out parameter. This construct makes it useful to call this method in a looping construct where another return type would/might make it a bit more complicated.

On further reflection one con could be a tendency to just keep adding out parameters to a method instead of properly encapsulating the logic.

Upvotes: 4

dco
dco

Reputation: 327

In C# you can't return multiple variables, so you might do the job by using the out parameter, if you don't want to go through a class (return a class with those multiple variables).

Upvotes: 0

Related Questions