When should I use out parameters?

后端 未结 10 1306
温柔的废话
温柔的废话 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:02

    Yes, it does make sense. Take this for example.

    String strNum = "-1";
    Int32 outNum;
    
    if (Int32.TryParse(strNum, out outNum)) {
        // success
    }
    else {
        // fail
    }
    

    What could you return if the operation failed in a normal function with a return value? You most certainly could not return -1 to represent a fail, because then there would be no differentiation between the fail-return value and the actual value that was being parsed to begin with. This is why we return a Boolean value to see if it succeeded, and if it did then we have our "return" value safely assigned already.

提交回复
热议问题