Saeid Saeid - 1 month ago 10
C# Question

C# Object property modified in the called function affect caller value

I defined a simple class with the following definition.
In this sample, I defined a simple class with a single string parameter. Then I instantiated this class and assigned a value to the parameter. I passed that instance to another function without specifying "ref" keyword. It means it should be passed by value instead of reference. But what I don't understand is the reason that the output displays "Second Modification" value as a result instead of "First Modification".

UPDATE 1:



I think my question was confusing. I know how "ref" and "pass by reference" working. I need to know why when I "pass by value", run-time still changes the value of the original instance. By the way, I couldn't find my answer in the proposed links.

UPDATE 2:



I asked this question two years ago. Now I understand all properties of an object (instance of a class) are reference type. It means when I pass an instance of a class to another method, they all behave as a reference to original member of the class.




public class MyClass
{
public String TestProperty { get; set; }
}

public class TestClass
{
public TestClass()
{
var myClass = new MyClass();
myClass.TestProperty = "First Modification";
MyFunction(myClass);
Console.WriteLine(myClass.TestProperty); // Output: "Second Modification"
}
void MyFunction(MyClass myClass)
{
myClass.TestProperty = "Second Modification";
}
}

Rik Rik
Answer

You can change the object passed to the method, but you can't change the reference itself without the ref keyword

public class MyClass
{
    public String TestProperty { get; set; }
}

public class TestClass
{
    public TestClass()
    {
        var myClass = new MyClass();
        myClass.TestProperty = "First Modification";

        MyFunction(myClass);
        Console.WriteLine(myClass.TestProperty); // Output: "First Modification"

        MyRefFunction(ref myClass);
        Console.WriteLine(myClass.TestProperty); // Output: "Third Modification"
    }
    void MyFunction(MyClass myClass)
    {
        myClass = new MyClass() { TestProperty = "Second Modification"};
    }

    void MyRefFunction (ref MyClass myClass)
    {
        myClass = new MyClass() { TestProperty = "Third Modification"};
    }
}

If you want to prevent the property being changed, you can make the setter non-public:

public String TestProperty { get; private set; }
Comments