Arguments in C#



In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment.


To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier. For simplicity, only the ref keyword is used in the examples in this topic.


Below is the difference between Pass by Value and Pass by Reference


Pass by Value Pass by Reference

Passes and argument by Value

Passes an argument by reference

Callee does not have any access to the underlying element in the calling code

Callee gives a direct reference to the programming element in the calling code

A copy of the data is sent to the callee

The memory address of the stored data is passed

Changes made to the passed variable do not affect the actual value

Changes to the value have an effect on original data.

If we are building multi-threaded application, then we don’t have to worry of objects getting modified by other threads. In distributed application pass by value can save the over network overhead to keep the objects in sync.

In pass by reference, no new copy of the variable is made, so overhead of copying is saved. This makes programs efficient especially when passing objects of large structs or classes.

Required more Memory