开发者

Why do I sometimes have to pass a class by reference and other times not?

I have a met开发者_如何学编程hod that takes List<Foobar> and Foobar as parameters. Foobar is a regular class with private variables, a constructor, and methods to operate on the data.

I modify both of the instances passed in the method but for some reason I have to pass Foobar with the ref keyword or else the changes do not stick when the method completes. I do not have to do this for the list.

I've noticed this a couple times recently in my programming. Usually when passing an instance of a class to the method, modifying it changes the instance, but sometimes it doesn't and it requires the ref keyword for changes to stick. It seems rather random in when it works. Does anyone know why this is?


If the value of a parameter change, like this:

parameter = new SomeValue();

then that change will only be seen by the caller using ref.

If instead you're changing the contents of an object which the caller passed a reference to, then that reference can be passed by value:

public void AppendHello(StringBuilder builder)
{
    // This changes the data within the StringBuilder object that the
    // builder variable refers to. It does *not* change the value of the
    // builder variable itself.
    builder.Append("Hello");
}

See my article on parameter passing for more information.

Note that if the parameter type is a struct instead of a class, then you won't be passing a copy of the reference to an object - you'll be passing the actual data itself. In that situation you'd need to use ref as well.


What do you mean by "modifying it". You can pass an object to a method and change its data, either by changing properties or adding elements to a generic list. However, you cannot change the actual object pointed to by that variable. In order to actually change, say Foobar to something else entirely, it needs to be passed by ref.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜