In C#, the Call by Reference is the structured approach for transferring values to function parameters. This mechanism allows functions to alter the original variable values directly as both formal and actual parameters point to the same variable. Modifying a parameter within the function can impact the original arguments. This concept is also referred to as Call by Address.
The <style> element is styled using CSS properties like background, border-radius, padding, margin, and text-align for a visually appealing design. Within the element, there is a placeholder-icon class with a specified font size and margin, as well as a placeholder-text class with a defined color and font size. The styling creates a structured and centered layout for the element.
Syntax:
It has the following syntax:
return_type Method_Name(ref dataType param_Name)
{
// Code to be Executed
}
Here, it is necessary to utilize the ref keyword when invoking the method.
Example:
Let's consider an example to illustrate the Call by Reference concept in C#.
Example
using System;
class C# Tutorial
{
static void ModifyValues(ref int num1, ref int num2) // Method to modify values using ref
{
num1 *= 3;
num2 += 7; // double the first number.
}
static void Main(string[] args)
{
Console.Write("Enter the First Number: "); //takes user input
int x = int.Parse(Console.ReadLine());
Console.Write("Enter the Second Number: ");
int y = int.Parse(Console.ReadLine());
Console.WriteLine("\nBefore modification, the values are:");
Console.WriteLine($"x = {x}, y = {y}");
ModifyValues(ref x, ref y); // Call the method with ref parameters
Console.WriteLine("\nAfter modification, the values are:");
Console.WriteLine($"x = {x}, y = {y}");
}
}
Output:
Enter the first number: 5
Enter the second number: 2
Before modification, the values are:
x = 5, y = 2
After modification, the values are:
x = 15, y = 9
Explanation:
In this instance, we employ the ref keyword to showcase the Call-by-reference mechanism. Following that, two integer parameters by reference undergo alterations through the ModifyValues function, where the initial value is tripled, and the second value is incremented by 7.
In the main function, it initially prompts the user to enter two integer values and displays their current values prior to any alterations. Following this, it invokes ModifyValues(ref x, ref y), which employs reference parameters to directly modify the original values.
Methods in C# Call by Reference:
Various techniques for Call by Reference in C# include:
1. Using ref in C# (Pass by Reference):
In C#, a variable can be passed by reference by utilizing the ref keyword. This signifies that modifications applied to the variable within the function will impact the initial value within the calling scope. The ref keyword empowers the function to interact with the genuine variable directly.
Example for Using Ref Keyword in C#:
Example
using System;
class C# Tutorial
{
static void DoubleValue(ref int num_ber)
{
num_ber *= 3; // Modifying the original value
}
static void Main()
{
int value = 14;
Console.WriteLine("Before modifying the value is: " + value);
DoubleValue(ref value); // Passing the variable by reference
Console.WriteLine("After modifying the value is: " + value);
}
}
Output:
Before modifying the value is: 14
After modifying the value is: 42
Explanation:
In this instance, an integer variable is passed by reference employing the ref keyword, allowing the function to modify the variable's original value. By utilizing num_ber as a reference parameter, the DoubleValue function alters the initial value of the variable by tripling it. Consequently, upon calling DoubleValue(ref value) within the main function, the adjustment persists, leading to a transformation of the value from 14 to 42.
2. Using Out in C# (Pass by Reference Without Initialization):
In C#, a function can send back multiple values by passing parameters by reference with the help of the out keyword. This keyword allows passing a variable that has not been initialized as an argument. However, the method must assign a value to the variable before it completes execution.
Why use Out Keyword in C#?
The out keyword proves to be particularly useful in scenarios where a function needs to provide multiple results but prefers not to employ intricate data structures such as tuples or objects. This keyword empowers a function to modify numerous variables simultaneously, eliminating the need for explicit return statements.
Example for Using Out Keyword in C#:
Example
using System;
class C# Tutorial
{
static void GetNumbers(out int num1, out int num2)
{
num1 = 10; // Assign value inside the method
num2 = 20;
}
static void Main()
{
int x, y;
GetNumbers(out x, out y);
Console.WriteLine("The First number is: " + x);
Console.WriteLine("The Second number is: " + y);
}
}
Output:
The First number is: 10
The Second number is: 20
Explanation:
This C# program enables a function to output multiple values by passing variables by reference with the use of the out keyword.
3. Using In keyword in C# (Pass by Read-Only Reference):
A variable can be provided as an immutable reference to a method in C# by utilizing the in keyword. This guarantees that the method is unable to alter the initial value. This approach proves beneficial when dealing with large structures or objects as it prevents unnecessary memory duplication while preserving the integrity of the original data.
Example for Using In keyword in C#:
Let's consider an example to showcase the In keyword in C#.
Example
using System;
struct LargeData
{
public int Number;
public string Text;
}
class C# Tutorial //defining a class
{
static void DisplayData(in LargeData data)
{
Console.WriteLine("Number: " + data.Number); //Shows the Number
Console.WriteLine("Text: " + data.Text); //Shows the Text
// data.Number = 115;
}
static void Main()
{
LargeData obj = new LargeData { Number = 70, Text = "Hello C# Tutorial" };
DisplayData(in obj); // using read-only reference
}
}
Output:
Number: 70
Text: Hello C# Tutorial
Explanation:
This demonstration illustrates the technique of providing a method with a read-only reference using the in keyword. The DisplayData method receives an integer (Num) and a string (Text) from the LargeData structure, ensuring read-only access and preventing redundant memory duplication.
When to Use Call by Reference in C#?
- Modifying Original Variables: It is useful when a method requires to modify a variable's original value instead of creating a copy.
- Working with Complex Data Types: It is suitable for modifying the state of large data structures, arrays, or objects.
- Returning Multiple Values: It can be useful when a method wants to return more values without depending on return values.
- Enhancing Code Flexibility: Functions can interact with variables, which makes code flexible and reusable.
Advantages of Call by Reference
Several advantages of Call by Reference are as follows:
- It helps to modify the original value.
- It is useful for a large data structure to modify the actual data.
- It doesn't make duplicate data to store values in memory space.
Disadvantages of Call by Reference:
Several disadvantages of Call by Reference are as follows:
- When several references refer to the same data, changing one reference affects all of them.
- The debugging becomes more challenging.
- As the function is passed by reference, it is no longer theoretically pure.
Conclusion
In the C# programming language, Call by Reference plays a crucial role by providing a means to manipulate the original data under controlled conditions. This capability facilitates necessary modifications while also supporting safety measures such as read-only access.
C# Call by Reference FAQs
1) What is the Call by Reference in C#?
In C#, Call by Reference is a technique used for passing values to function arguments. This approach enables functions to modify the values of actual variables directly, as both the actual and formal parameters point to the same variable. Any changes made to the parameter within the function can impact the original arguments.
In C#, the distinction between Call by Value and Call by Reference lies in how arguments are passed to methods:
- Call by Value involves passing a copy of the value of the actual parameter to the method. Any changes made to the parameter within the method do not affect the original value.
- Call by Reference, on the other hand, passes the memory address of the actual parameter. This means any modifications made to the parameter within the method will reflect on the original value outside the method scope.
The primary difference between call by value and call by reference in C# ```
returntype MethodName(ref dataType param_Name)
{
// Code to be Executed
}
When using Call by Value, a duplicate of the value is sent to the function. This method covers fundamental and uncomplicated data types such as integers, floating-point numbers, characters, and more.
Pass by Reference: The function receives the memory address of the value as an argument. This technique is commonly employed for handling intricate data types such as arrays, structures, strings, and more.
3) What are the benefits of Pass by Reference in C#?
The numerous benefits of Call by Reference in C# are as follows:
- Call by Reference alters the original value, avoiding the need for duplicating data in memory storage.
- This approach eliminates the creation of redundant data to store values in memory.
4) How is Call by Reference implemented in C#?
Call by Reference is executed in C# through the utilization of the ref or out keyword.
- ref: It is essential to initialize the variable when employing the ref keyword.
- Out: Unlike ref, there is no need to initialize the variable before assigning a value when using the out keyword.
5) What variances exist between the ref and out keywords?
Several variances between the ref and out keyword are outlined below:
| ref | out |
| --- | --- |
| The variables should be initialized, when the ref keyword is used. | The variables doesn't require to initialized before passing the value. |
| We can modify the value within the method. | We should be assign the value inside the method. |
| The data may be passed in a bidirectional manner. | The data may be passed through a unidirectional manner. |