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

前端 未结 6 1192
傲寒
傲寒 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:54

    I think the answer depends on the semantics of what the function is doing, and the relationship between the two values.

    For example, the TryParse methods take a out parameter to accept the parsed value, and return a bool to indicate whether or not the parse succeeded. The two values don't really belong together, so, semantically, it makes more sense, and the intent of the code is easier to read, to use the out parameter.

    If, however, your function returns X/Y coordinates of some object on the screen, then the two values semantically belong together and it would be better to use a struct.

    I'd personally avoid using a tuple for anything that will be visible to external code becuase of the awkward syntax for retrieving the members.

提交回复
热议问题