Object passed as parameter to another class, by value or reference?

前端 未结 7 1691
闹比i
闹比i 2021-02-18 21:12

In C#, I know that by default, any parameters passed into a function would be by copy, that\'s, within the function, there is a local copy of the parameter. But, what about when

7条回答
  •  有刺的猬
    2021-02-18 22:07

    An Object if passed as a value type then changes made to the members of the object inside the method are impacted outside the method also. But if the object itself is set to another object or reinitialized then it will not be reflected outside the method. So i would say object as a whole is passed as Valuetype only but object members are still reference type.

            private void button1_Click(object sender, EventArgs e)
        {
            Class1 objc ;
             objc = new Class1();
            objc.empName = "name1";
            checkobj( objc);
            MessageBox.Show(objc.empName);  //propert value changed; but object itself did not change
        }
        private void checkobj ( Class1 objc)
        {
            objc.empName = "name 2";
            Class1 objD = new Class1();
            objD.empName ="name 3";
            objc = objD ;
            MessageBox.Show(objc.empName);  //name 3
        }
    

提交回复
热议问题