CallByValue&Reference
1.Call by Value:
- Call by value is a method of passing arguments to a function where the actual value of the argument is passed to the function.
- In call by value, the function receives a copy of the argument's value, not the original variable.
- Changes made to the parameter inside the function do not affect the original value outside the function.
- Primitive data types like integers, floats, and characters are typically passed by value.
Example in C#:
void Increment(int x) { x++; // Increment the copy of x } int num = 10; Increment(num); // Call by value Console.WriteLine(num); // Output: 10 (original value unchanged)
2.Call by Reference:
- Call by reference is a method of passing arguments to a function where the reference (memory address) of the variable is passed to the function.
- In call by reference, the function receives a reference to the original variable, allowing it to modify the original value.
- Changes made to the parameter inside the function affect the original value outside the function.
- Objects, arrays, and explicitly using
reforoutkeywords in C# enable call by reference.
Example in C#:
void Increment(ref int x) { x++; // Increment the original x } int num = 10; Increment(ref num); // Call by reference Console.WriteLine(num); // Output: 11 (original value modified)
In summary, call by value passes a copy of the variable's value to the function, while call by reference passes a reference to the variable's memory address, allowing the function to modify the original value.
Comments
Post a Comment