C# – Difference between passing variables by reference and by value

A reader recently asked about “pointers” in C++, and if we use them in C#. That led to the C# concept of variables being “reference types” or “value types” – which I’ll explain here.

 

Which variables are value type, and which are reference type?

When you create a variable, you declare its datatype. You can use the “var” keyword, instead of the datatype. However, the .NET compiler determines what the datatype is, and uses the actual datatype when it compiles your program.

Some datatypes (mostly the built-in .NET datatypes, like numbers and booleans) are value types. Others (strings, and the classes you create for your project) are usually reference types.

 

How do they act differently?

When you create (instantiate) a variable, it is placed at a location in memory.

If you copy a value type variable to another variable, the value of that variable is used, and gets its own new place in memory (for the new variable). This also includes when you pass a value type variable as a parameter in a function. The function copies the value from the original variable into the parameter variable.

So, if you make any changes to the second variable, it does not touch the original variable’s memory.

Here is a function showing what happens when a value type variable is copied to another variable:

 

This is what happens when a value type variable is passed to a function, and modified inside the function:

 

When you copy a reference type variable (including passing it to a function), another instance of the variable is not created in memory. Instead, .NET passes a reference/pointer to the original variable’s location in memory.

Any changes you make to the new variable are made to the location in memory where the variable was originally created. So, if you look at the original variable, you will see that its value has changed.

Here is how a reference type variable is modified, when copied to another variable:

 

And here is what happens when a reference type variable is passed to a function:

 

Passing a value type variable as a reference

You can pass a value type variable to a function, and have it treated like a reference type – any modifications inside the function will happen to the original variable.

To pass a value type variable as a reference, you must include “ref” in the function’s parameter list, and when you call the function, like this:

 

 

2 thoughts on “C# – Difference between passing variables by reference and by value

Leave a Reply

Your email address will not be published. Required fields are marked *