Sobes.tech
Junior — Middle

What is the difference between passing data to a method by reference and by value?

sobes.tech AI

Answer from AI

In C#, data can be passed to a method mainly in two ways: by value and by reference.

  • By value (default): a copy of the variable's value is passed to the method. Changes inside the method do not affect the original variable outside.

  • By reference (using ref or out keywords): a reference to the original variable is passed. Changes inside the method are reflected in the original variable.

Example:

void ChangeValue(int x) {
    x = 10; // changes the copy
}

void ChangeValueRef(ref int x) {
    x = 10; // changes the original
}

int a = 5;
ChangeValue(a);
Console.WriteLine(a); // Outputs 5

ChangeValueRef(ref a);
Console.WriteLine(a); // Outputs 10

Thus, passing by value protects the original data from changes inside the method, while passing by reference allows the method to modify the original data.

What is the difference between passing data to a… - sobes.tech