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

前端 未结 7 1696
闹比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:02

    Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        public class Employee
        {
            public string Name { get; set; }
        }
    
        public class MyClass
        {
            public Employee EmpObj;
    
            public void SetObject(Employee obj)
            {
                EmpObj = obj;
            }
        }
    
        public class Program
        {
           static void Main(string[] args)
            {
                Employee someTestObj = new Employee();
                someTestObj.Name = "ABC";
    
                MyClass cls = new MyClass();
                cls.SetObject(someTestObj);
    
                Console.WriteLine("Changing Emp Name To xyz");
                someTestObj.Name = "xyz";
    
                Console.WriteLine("Accessing Assigned Emp Name");
                Console.WriteLine(cls.EmpObj.Name); 
    
               Console.ReadLine();
           }       
        }
     }
    

提交回复
热议问题