what is the pros and cons of using out parameter

前端 未结 4 1098
囚心锁ツ
囚心锁ツ 2021-01-19 10:22

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.

相关标签:
4条回答
  • 2021-01-19 11:00

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

    0 讨论(0)
  • 2021-01-19 11:02

    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.

    0 讨论(0)
  • 2021-01-19 11:06

    As you said, without out parameter, you can only return one value, out keyword allow you "return" more than one value

    0 讨论(0)
  • 2021-01-19 11:11

    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.

    0 讨论(0)
提交回复
热议问题