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
236 views
in Technique[技术] by (71.8m points)

c# - Best practice: ref parameter or return value?

Actually I am doing a list as a reference parameter as follows:

public static List ListMethod(List result)

I saw some people doing in this way too:

public static void ListMethod(ref List result)

If I'm not wrong, "my" method also takes the list as reference parameter, and you should be able to use it just the same way as "other" does in his method.

But it seems more "clean" to me that you enter a parameter, do something with it and return it in the methods return value.

Any good arguments for or against one method or the other?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's likely that you don't need to use ref - but there is a difference.

Usually when I see people using ref for reference type parameters, it's because they don't understand how parameter passing works. But if your method has something like this:

result = new List();
...

then in the first case the caller won't see the change, whereas in the second case the caller's variable will be changed to refer to the new object.

See my article on parameter passing for a lot more detail.


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

...