Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need "out" parameters?

Tags:

c#

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?

like image 569
InfoLearner Avatar asked Nov 29 '10 11:11

InfoLearner


2 Answers

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.

like image 109
Darin Dimitrov Avatar answered Dec 11 '22 11:12

Darin Dimitrov


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.

like image 24
BenW Avatar answered Dec 11 '22 12:12

BenW