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?
If the value of a parameter change, like this:
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:
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
refas well.