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

前端 未结 7 1912
闹比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 21:43

    I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.

    In other words, my Increment method modifies its parameter myClass everytime its called.

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            Console.WriteLine(myClass.Value);  // Displays 1
            Increment(myClass);
            Console.WriteLine(myClass.Value);  // Displays 2
            Increment(myClass);
            Console.WriteLine(myClass.Value);  // Displays 3           
            Increment(myClass);
            Console.WriteLine(myClass.Value);  // Displays 4
            Console.WriteLine("Hit Enter to exit.");
            Console.ReadLine();
        }
    
        public static void Increment(MyClass myClassRef)
        {
            myClassRef.Value++;
        }
    }
    
    public class MyClass
    {
        public int Value {get;set;}
        public MyClass()
        {
            Value = 1;
        }
    }
    

提交回复
热议问题