Reputation: 8851
I have a method 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?
Upvotes: 3
Views: 162
Reputation: 5291
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.
Upvotes: 0
Reputation: 1502336
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.
Upvotes: 7