Modify method parameter within method or return result

前端 未结 7 2408
余生分开走
余生分开走 2020-12-05 02:47

What is the difference between

private void DoSomething(int value) {
    value++;
}

and

private int DoSomething(int value)          


        
7条回答
  •  旧时难觅i
    2020-12-05 03:00

    In your first example, the int parameter value is incremented, but is destroyed when the method ends, you cannot get the value outside the method, unless you use the ref or out keywords.

    For example:

    private int DoSomething(ref int value) {
       return value++;
    }
    
    // ...
    int myValue = 5;
    DoSomething(ref myValue);
    // Now myValue is 6.
    

    Ref and out parameter passing modes are used to allow a method to alter variables passed in by the method caller. The main difference between ref and out may be subtle but it's important.

    Each parameter passing mode is designed to suite different programming needs.

    The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the method is required to assign to the out parameter before returning.

    One way to think of out parameters is that they are like additional return values of a method. They are convenient when a method should return more than one value.

    The ref parameters causes the arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.

    Do not confuse the concept of passing by reference with the concept of reference types.

    The two concepts are not related; a method parameter can be modified by ref regardless of whether it is a value type or a reference type, there is no boxing of a value type when it is passed by reference.

提交回复
热议问题