Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

c# - Modify method parameter within method or return result

What is the difference between

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

and

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

when used as either

DoSomething(value);

versus

value = DoSomething(value);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...