C# Pass by Reference: A Comprehensive Guide
Why C# Pass by Reference Is Important in Object-Oriented Programming
C# Pass by reference plays a major role in object-oriented programming (OOP) because it lets users configure the memory location of a variable without ever passing in its actual value.
To truly understand this idea, you have to know what it means to pass a parameter by reference; that is, to transfer the value of an argument in the calling function to the parameters of the corresponding called function.
As a refresher, C# is a general-purpose language, developed by Microsoft to run all kinds of applications on the .NET framework. C# supports many operations including variables, methods, objects, properties, and events. C# methods can take multiple parameters to generate the desired output.
With that in mind, there are two ways to pass a parameter into a method: by value or by reference.
What Distinguishes C# Pass by Reference from Pass by Value?
The easier option is to pass parameters by value, copying a variable into another function or method to be altered in some way.
Whenever a simple variable becomes a method parameter, it is assigned a certain value. This value stored in the original variable gets copied to the method, thereby creating a local environment for changing or modifying them without affecting the passed in variable.
Last Updated August 2024
Master C# Programming from A to Z. Dive deep into .NET, OOP, Clean Code, LINQ, WPF, Generics, Unit Testing, and more. | By Denis Panjuta, Tutorials.eu by Denis Panjuta
Explore CourseEffectively, it prevents the value from being altered, while limiting change to just the variable in the calling method. The point of this is to avoid overriding the real value of a variable, in the event that a program must retain it in the calling method as well.
The concept of C# Pass by value is summarized in this code demo:
class PassingValByVal
{
static void SquareIt(int x)
{
x *= x;
System.Console.WriteLine("The value inside the method: {0}", x);
}
static void Main()
{
int n = 5;
System.Console.WriteLine("The value before calling the method: {0}", n);
SquareIt(n);
System.Console.WriteLine("The value after calling the method: {0}", n);
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
The value inside the method: 25
The value after calling the method: 5
In the class PassingValByVal, the argument “int x” is passed in by value, implying that changing x won’t affect its initial value. The static void method, SquareIt(n) should take n=5 from x as the local variable to square. Unlike public void methods, the static ones can be called without having to instantiate the class.
As for the output, one should expect the value of x to start at 5 and square to equal 25 once inside the calling method, with the value under Main still being 5. Simply put, the integer of n is pasted into the parameter x, which gets squared in the method. The outcome confirms that int n = 5 has replaced int x in SquareIt().
Top courses in C# (programming language)
Another Approach to Using Variables in Methods
This concept is also known as C# pass by reference. It requires initializing the variable prior to passing it in as a method argument. But before you jump into that, it would be best to learn about C# pass by value as a prerequisite. Check out this tutorial for a detailed explanation on how to pass type variables as parameters using a ref int inside the argument.
It’s also slightly more complicated because the variable’s reference is being passed to a method parameter. This means that the method is initiated on references instead of directly on values, in turn accessing variables within the call function. It often applies to class object fields but not data types such as integers or Booleans.
To clearly demonstrate this concept, take a look at the code example below:
class Person
{
public int age;
}
class Program
{
static void Square(Person a, Person b)
{
a.age = a.age * a.age;
b.age = b.age * b.age;
Console.WriteLine(a.age+" "+b.age);
}
static void Main(string[] args)
{
Person p1 = new Person();
Person p2 = new Person();
p1.age = 5;
p2.age = 10;
Console.WriteLine(p1.age +" "+p2.age);
Square(p1, p2);
Console.WriteLine(p1.age + " " + p2.age);
Console.ReadLine();
}
}
In the code block, the class Person is declared and contains the public type integer age. It contains a static void main method with string args as well as two objects (p1 and p2) of the Person class, serving as new instances with specific values of 5 and 10 indicated on the console.
The next step is to pass reference types p1 and p2 as parameters into the Square method to get the referenced value from the static Square method under the Program class. They are displayed as a.age and b.age set equal to their squares.
For this class program, the method operates on the references instead of their values, thus modifying the call function variables.
When P1 and P2 are read from the console, the resulting age variable of both objects are being accessed to square their values. If the p1 and p2 object values are listed in the Main method, they would have the updated age value, proving that the parameters did pass into Square.
The output should print out the following:
5 10
25 100
25 100
A Short Recap of Pass by Reference
In some cases, you might have to work with a string constant, which means having to search for specific substrings. If you ever come across such a problem, it would be helpful to reference a variable and use the IndexOf method to iterate through each character. This lets you decide what string should belong to the output.
C# pass by reference is a crucial feature for changing values inside of functions to drive programs with multiple classes or methods, without having to destroy objects each time they are assigned a different parameter. Not only that, but also the concept has been implemented into web elements, such as pressing the submit button or taking a user input and giving feedback .
As discussed earlier, C# pass by reference is an efficient workaround for building interactive applications, including many Microsoft products and services. In fact, the language itself is the backbone of virtual machines and web programs, helping to modernize C/C++ systems with an object-oriented outlook.
If you want to learn C# basics on your own time, you may find this article on C# components and the syntax to be a great introduction to C# programming.
There are tons of top-rated courses on C# if you plan on building apps or games.
Frequently Asked Questions
Is C# pass by value or reference?
By default, C# is pass by value since the ref or out keyword must be explicitly stated to tell the compiler it is C# by reference. On top of that, the moment a method is called, it declares a new variable where its argument is copied to the void method, except that no object is being created. There are other cases where it depends on the types of local variables passed in. Integers and Booleans are always passed by value, but objects and strings are actually passed by reference instead.
How do you pass a value by reference in C#?
To pass a value by reference, begin by initializing a variable and setting its value. Now, declare a method in the following syntax: Name(ref var). Inside the brackets is the value type parameter. Both of these must be placed into the static void Main() method of the object class. Afterward, construct a public static void of the declared method, as this is where the referenced variable is converted to a new value. Be sure that the calling and default methods have the ref keyword in the argument. To check the results, type in Console.WriteLine(ref-type var).