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

parameters - confusion with value type and reference type in c#

I have bit confusion about parameters. When we should have to use reference parameter and when should have to use value type parameters while programming with methods/functions in c# ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to be very clear on the distinction between reference types vs value types, and "by value" parameters vs "by reference" parameters.

I have articles on both topics:

The two interact somewhat when using a "by value" parameter which is a reference type: in this case the value which copied by value is the reference itself; you can still modify the object that the reference refers to:

void SomeMethod(StringBuilder x)
{
    x.Append("Modified");
}
...

StringBuilder builder = new StringBuilder();
SomeMethod(builder);
Console.WriteLine(builder.ToString()); // Writes "Modified"

Note that this isn't the same thing as pass-by-reference semantics... if SomeMethod were changed to include:

x = null;

then that wouldn't make the builder variable null. However, if you also changed the x parameter to be ref StringBuilder x (and changed the calling code appropriately) then any changes to x (such as setting it to null) would be seen by the caller.

When designing your own API, I would strongly advise you to almost never use ref or out parameters. They can be useful occasionally, but usually they're an indication that you're trying to return multiple values from a single method, which is often better done with a type specifically encapsulating those values, or perhaps a Tuple type if you're using .NET 4. There are exceptions to this rule, of course, but it's a good starting point.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...