InfoLearner
InfoLearner

Reputation: 15598

Why do we need "out" parameters?

I understand that "out" are just like "ref" types, except that out variables do not have to be initialised. Are there any other uses of "out" parameters? Sometimes I see their use in callback methods but I never understood how they actually work or why we need them instead of global level ref variables?

Upvotes: 8

Views: 463

Answers (4)

RameshVel
RameshVel

Reputation: 65877

2 main differences are there

  1. Unlike ref it doesn't expect the variable to be initialized.
  2. when using OUT, called function is responsible of assigning the value not callee.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

Why would you want to have to initialize something in the calling method, with no guarantee that the called method itself would overwrite the variable if the method completes normally? Those are the benefits that out parameters give you.

Basically I think of out parameters as "oops, I need to return more than one value" indicators. I'd prefer to use tuples myself, but of course they only made it into .NET 4... and without explicit language support they're slightly more awkward to use than would be ideal, too.

Upvotes: 3

BenW
BenW

Reputation: 1312

One of the biggest examples is the TryParse methods, you want to be able to check if something can be converted, and usually if it can be converted you want the converted value. Otherwise its just another way to pass objects back to the calling method.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

out parameters enforce the contract between the caller and the callee (the function being called) by explicitly specifying that the callee will initialize them. On the other hand when using ref parameters all we know is that the callee could modify them but it is the caller's responsibility to initialize them.

Upvotes: 14

Related Questions