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

。_饼干妹妹 提交于 2019-12-04 20:55:36

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; }

That is the expected behavior. What ref would allow you to do is create a new object in MyFunction and assign it to the myClass parameter and have the new object available outside the method.

   void MyFunction(ref MyClass myClass)
   {
     myClass = new MyClass(); //this new instance will be accessible outside the current method
   }

Have a look at http://msdn.microsoft.com/en-us/library/14akc2c7.aspx for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!