Modify method parameter within method or return result

前端 未结 7 2396
余生分开走
余生分开走 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:11

    Simply the first one won't work because you're operating on a copy of value.

    You could do something like

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

    and call it like

    DoSomething(ref value);
    

    This changes value to be passed in by reference. But really the only reason to do this is if you want to return more than one thing from your function. And normally there are better ways.

    For extra bonus knowledge, there's also the out keyword which is similar to ref, but doesn't require value to be initialised first.

提交回复
热议问题