There are value types and reference types in c#.

Value types hold the direct data i.e value  or object where as the reference types store the reference to a location in memory of the data or value or object.

  • Value types are primitive types like int, float, Structs, enum.
  • Reference types are classes, delegates, interfaces.
  • Strings are immutable reference types.

Different methods of parameter passing.

  1. Value types Passed By Value.
  2. Value types Passed By Reference.
  3. Reference types Passed By Value.
  4. Reference types Passed By Reference.

Value types Passed By Value

When Value types are passed by value then a new memory is created for the parameters and it starts with the passed value.

Any change to the parameters in the body of the function will not have any effect on the arguments in the calling function.

Value types Passed By Reference

When value types are passed by Reference then the reference of the arguments are passed on to the parameters i.e now parameter variable holds the reference of the argument variables.

Hence any change to the argument values in the called function reflects the value of the parameters in the calling function.

Reference types Passed By Value

In Reference types passed by value a copy of the value i.e. reference of the original memory location held in the reference variable is passed. Hence when a change is made in the called function variable then the change is not reflected in the called function. This is so because a copy of the reference is made which means it is just passed by value.

Eg:

P =”Honey Comb”  

Now here P is mapping to one particular memory location. It is either a variable or object etc.

If P is assigned to Q then Q will also point to same memory location since P is a reference type and its value i.e. a memory location is passed to Q.

P=Q

P= “Honey Comb”

Q=”Honey Comb”  

Now  if Q= ” Ginger Bread” then Q will now map to a different memory location while P will still map to its original memory location.

P=”Honey Comb”

Reference types Passed By Reference

When reference types are passed by reference , the actual reference of the variable itself will be passed not the copy of the reference to which the variable is pointing to i.e in our example the address of the P is passed to Q rather than the P’s value (as it’s the case in passed by value)so any change in Q will result a change in P. Here the assignment Q=B would have resulted in P also to point to B since Q contains the address of P.

Reference types are passed using ref keyword.

P= “Honey Comb”

Q=”Honey Comb”

Q= ” Ginger Bread” reflects P to map to Ginger Bread

Happy coding.

 

Advertisements