When should I use out parameters?

后端 未结 10 1341
温柔的废话
温柔的废话 2020-12-08 06:34

I don\'t understand when an output parameter should be used, I personally wrap the result in a new type if I need to return more than one type, I find that a lot easier to w

10条回答
  •  情话喂你
    2020-12-08 07:01

    Definitely, out parameters are intended to be used when you have a method that needs to return more than one value, in the example you posted:

    public void Do(int arg1, int arg2, out int result)
    

    It doesn't makes much sense to use an out parameter, since you are only returning one value, and that method could be used better if you remove the out parameter and put a int return value:

    public int Do(int arg1, int arg2)
    

    There are some good things about out parameters:

    1. Output parameters are initially considered unassigned.
      • Every out parameter must be definitely assigned before the method returns, your code will not compile if you miss an assignment.

    In conclusion, I basically try use out params in my private API to avoid creating separate types to wrap multiple return values, and on my public API, I only use them on methods that match with the TryParse pattern.

提交回复
热议问题