Returning two values, Tuple vs 'out' vs 'struct'

前端 未结 6 1191
傲寒
傲寒 2020-12-24 04:23

Consider a function which returns two values. We can write:

// Using out:
string MyFunction(string input, out int count)

// Using Tuple class:
Tuple

        
6条回答
  •  无人及你
    2020-12-24 04:59

    You did not mention one more option, which is having a custom class instead of struct. If the data has semantics associated to it which can be operated upon by functions, or the instance size is big enough (> 16 bytes as a rule of thumb), a custom class may be preferred. Use of "out" is not recommended in public API because of its association to pointers and requiring understanding of how reference types work.

    https://msdn.microsoft.com/en-us/library/ms182131.aspx

    Tuple is good for internal use, but it usage is awkward in public API. So, my vote is between struct and class for public API.

提交回复
热议问题