Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by ref?

Tags:

c#

.net

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?

like image 811
theringostarrs Avatar asked Jul 20 '09 05:07

theringostarrs


People also ask

What is meant by passing by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

What is passing by reference vs passing by value?

“Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.

Is passing by reference good?

Passing value objects by reference is in general a bad design. There are certain scenarios it's valid for, like array position swapping for high performance sorting operations. There are very few reasons you should need this functionality. In C# the usage of the OUT keyword is generally a shortcoming in and of itself.

Is pass by reference a copy?

In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.


1 Answers

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.

like image 70
statenjason Avatar answered Oct 20 '22 00:10

statenjason