C# – Passing by ref

.net, c++

I am still confused about passing by ref.

If I have a Cache object which I want to be accessed/available to a number of objects, and I inject it using constructor injection. I want it to affect the single cache object I have created. eg.

public class Cache {   public void Remove(string fileToRemove) {      ...   }}public class ObjectLoader {   private Cache _Cache;   public ObjectLoader(Cache cache) {   }   public RemoveFromCacheFIleThatHasBeenDeletedOrSimilarOperation(string filename) {      _Cache.Remove(fileName);   }}

Should I be using ref when I pass the Cache into the ObjectLoader constructor?

Best Solution

No you do not need to use the ref keyword in this situation.

Cache is a class, it is a reference type. When a reference is passed into a method, a copy of the reference (not the object itself) is placed into your parameter. Both references, inside and outside, of the method are pointing to the same object on the heap, and modification of the object's fields using one will be reflected in the other.

Adding ref to your method call passes in the original reference. This is useful in a situation where you would be reassigning (ie. by calling new) the location the reference points to from within a calling method.