DEV Community

Cover image for Call by Value vs. Call by Reference in C#
Shreyans Padmani
Shreyans Padmani

Posted on

Call by Value vs. Call by Reference in C#

One of the most frequently asked interview questions in C# is:

๐Ÿ‘‰ What is Call/Pass by Value vs. Call/Pass by Reference โ“

Many developers, especially beginners, often respond with:
โŒ Primitive types are passed by value, and reference types are passed by reference.

โš  This is a misconception!

In this blog, Iโ€™ll break down the real difference between Call by Value and Call by Reference in C# with clear explanations and examples. Let's dive in!

Call by Value in C#

By default, in .NET, everything (value types & reference types) is passed by value, unless explicitly stated otherwise.

How It Works
When you pass a variable by value, a copy of the original variable is passed. Any modifications made inside the method wonโ€™t affect the original variable.

Call by Reference in C#

To pass a variable by reference, you must explicitly use the ref or out keyword. This means the method receives a reference to the original variable instead of a copy, and changes will affect the original value.

Final Takeaways

โœ” By default, everything in C# is passed by value, whether itโ€™s a value type or reference type.
โœ” To modify the original variable, you must use ref or out.
โœ” Reference types are NOT automatically passed by reference. Their reference is passed by value unless explicitly stated otherwise.

Top comments (0)