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

前端 未结 6 1179
傲寒
傲寒 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 05:07

    They each have their pros and cons.

    Out parameters are fast and cheap but require that you pass in a variable, and rely upon mutation. It is almost impossible to correctly use an out parameter with LINQ.

    Tuples make garbage collection pressure and are un-self-documenting. "Item1" is not very descriptive.

    Custom structs can be slow to copy if they are large, but are self-documenting and are efficient if they are small. However it is also a pain to define a whole bunch of custom structs for trivial uses.

    I would be inclined to the custom struct solution all other things being equal. Even better though is to make a function that only returns one value. Why are you returning two values in the first place?

    UPDATE: Note that tuples in C# 7, which shipped six years after this article was written, are value types and hence less likely to create collection pressure.

提交回复
热议问题