We can pass value type parameters by two types -
All value type goes to stack so when you pass a parameter to another method as value type. It allocates a new memory location on stack. Let's see blow example -
Memory allocation on value type parameters -
So the only problem is passing value type parameter is if we have to pass large value type so it will need memory(allocate new memory space) and will be expensive as well while copying data every time. It will be inefficient if we will call this method multiple times. So to avoid this we can pass the value type as reference and this will just pass a pointer to that value.
Pass value type parameter by Reference- We can pass value type parameter as reference by using ref keyword. The original value of the parameter will be changed after calling the method.
So this will change the original value of x and will print 7 and 7. This allocates memory efficiently and just create a pointer to the original address space. So whenever you try to fetch the value it will point to the original location - have a look on below screenshot -
Passing reference type as a parameter is almost same as passing value type as reference will discuss this in my next article.
Hope you enjoyed reading this article.
- Pass value type by value
- Pass value type by reference
All value type goes to stack so when you pass a parameter to another method as value type. It allocates a new memory location on stack. Let's see blow example -
Memory allocation on value type parameters -
So the only problem is passing value type parameter is if we have to pass large value type so it will need memory(allocate new memory space) and will be expensive as well while copying data every time. It will be inefficient if we will call this method multiple times. So to avoid this we can pass the value type as reference and this will just pass a pointer to that value.
Pass value type parameter by Reference- We can pass value type parameter as reference by using ref keyword. The original value of the parameter will be changed after calling the method.
So this will change the original value of x and will print 7 and 7. This allocates memory efficiently and just create a pointer to the original address space. So whenever you try to fetch the value it will point to the original location - have a look on below screenshot -
Passing reference type as a parameter is almost same as passing value type as reference will discuss this in my next article.
Hope you enjoyed reading this article.