How do you return two values from a single method?

后端 未结 22 851
谎友^
谎友^ 2020-12-11 00:58

When your in a situation where you need to return two things in a single method, what is the best approach?

I understand the philosophy that a method should do one t

22条回答
  •  清歌不尽
    2020-12-11 01:45

    I will usually opt for approach #4 as I prefer the clarity of knowing what the function produces or calculate is it's return value (rather than byref parameters). Also, it lends to a rather "functional" style in program flow.

    The disadvantage of option #4 with generic tuple classes is it isn't much better than returning a collection (the only gain is type safety).

    public IList CalculateStuffCollection(int arg1, int arg2)
    public Tuple CalculateStuffType(int arg1, int arg2)
    
    var resultCollection = CalculateStuffCollection(1,2);
    var resultTuple = CalculateStuffTuple(1,2);
    
    resultCollection[0]    // Was it index 0 or 1 I wanted? 
    resultTuple.A          // Was it A or B I wanted?
    

    I would like a language that allowed me to return an immutable tuple of named variables (similar to a dictionary, but immutable, typesafe and statically checked). But, sadly, such an option isn't available to me in the world of VB.NET, it may be elsewhere.

    I dislike option #2 because it breaks that "functional" style and forces you back into a procedural world (when often I don't want to do that just to call a simple method like TryParse).

提交回复
热议问题