开发者

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 ac开发者_如何学Ctually work or why we need them instead of global level ref variables?


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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜