Modify method parameter within method or return result

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

What is the difference between

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

and

private int DoSomething(int value)          


        
相关标签:
7条回答
  • 2020-12-05 03:23

    You are talking about the difference between passing by reference and passing by value, which is conceptually similar to the idea of value types vs reference types.

    If you pass a value type into the method, you have to use the second example; otherwise you are just incrementing an integer that exists inside the scope of DoSomething(). Try it: if you execute your first example, after DoSomething() has run, the value of your int will be unchanged.

    However, if you are passing in something other than a value type (say object foo), you are actually passing a reference to the original object. Anything you do to it inside DoSomething() will take effect outside the method as well, since you are still referring to the same object.

    You can accomplish what you're attempting in the first example by writing:

    void DoSomething(ref int value)
    

    That instructs .NET to pass a reference to the item regardless of whether it is a value type.

    See this writeup on Value Types vs Reference Types on MSDN for a more detailed look.

    Additionally, as zodoz points out (upvote appropriately), by returning value++ you are returning and then incrementing. To return the incremented value, use ++value.

    0 讨论(0)
提交回复
热议问题