Sobes.tech
Junior — Middle

What is the difference between value-passed data types and reference-passed data types?

sobes.tech AI

Answer from AI

In C#, data types are divided into value types and reference types, and this affects how data is passed:

  • Pass by value:

    • The actual value is copied.
    • Changes inside the method do not affect the original.
    • Examples: int, double, struct.
  • Pass by reference:

    • A reference to the object in memory is copied.
    • Changes inside the method reflect on the original object.
    • Examples: class, string (although strings are immutable), arrays.

Example:

void ModifyValue(int x) {
    x = 10; // only the local copy will change
}

void ModifyReference(Person p) {
    p.Name = "Ivan"; // the object referenced by p will change
}

int a = 5;
ModifyValue(a);
Console.WriteLine(a); // 5

Person person = new Person { Name = "Peter" };
ModifyReference(person);
Console.WriteLine(person.Name); // Ivan

Thus, understanding the difference is important for managing data state and preventing unexpected changes.

What is the difference between value-passed data… - sobes.tech