List passed by ref - help me explain this behaviour

后端 未结 8 2309
名媛妹妹
名媛妹妹 2020-12-02 05:39

Take a look at the following program:

class Test
{
    List myList = new List();

    public void TestMethod()
    {
        myList.Add         


        
8条回答
  •  日久生厌
    2020-12-02 06:31

    Here is an easy way to understand it

    • Your List is an object created on heap. The variable myList is a reference to that object.

    • In C# you never pass objects, you pass their references by value.

    • When you access the list object via the passed reference in ChangeList (while sorting, for example) the original list is changed.

    • The assignment on the ChangeList method is made to the value of the reference, hence no changes are done to the original list (still on the heap but not referenced on the method variable anymore).

提交回复
热议问题